From a50654ef4d8f069e0b3b2612f7241681f20317b9 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 14 Jan 2026 15:13:54 -1000 Subject: [PATCH] [modbus_controller] Use stack buffers instead of str_sprintf/str_snprintf --- .../modbus_controller/modbus_controller.h | 8 ++++++-- .../text_sensor/modbus_textsensor.cpp | 16 ++++++++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/esphome/components/modbus_controller/modbus_controller.h b/esphome/components/modbus_controller/modbus_controller.h index 6ed05715cb..466598e9cd 100644 --- a/esphome/components/modbus_controller/modbus_controller.h +++ b/esphome/components/modbus_controller/modbus_controller.h @@ -285,8 +285,12 @@ class ServerRegister { case SensorValueType::S_QWORD_R: return std::to_string(value); case SensorValueType::FP32_R: - case SensorValueType::FP32: - return str_sprintf("%.1f", bit_cast(static_cast(value))); + case SensorValueType::FP32: { + // max 48: float with %.1f can be up to 41 chars (3.4e38 → 39 digits + sign + decimal + 1 digit) + null + char buf[48]; + snprintf(buf, sizeof(buf), "%.1f", bit_cast(static_cast(value))); + return buf; + } default: return std::to_string(value); } diff --git a/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp b/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp index 89e86741b0..c50e8317fa 100644 --- a/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp +++ b/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp @@ -16,12 +16,20 @@ void ModbusTextSensor::parse_and_publish(const std::vector &data) { while ((items_left > 0) && index < data.size()) { uint8_t b = data[index]; switch (this->encode_) { - case RawEncoding::HEXBYTES: - output_str += str_snprintf("%02x", 2, b); + case RawEncoding::HEXBYTES: { + // max 3: 2 hex digits + null + char hex_buf[3]; + snprintf(hex_buf, sizeof(hex_buf), "%02x", b); + output_str += hex_buf; break; - case RawEncoding::COMMA: - output_str += str_sprintf(index != this->offset ? ",%d" : "%d", b); + } + case RawEncoding::COMMA: { + // max 5: ","(1) + uint8(3) + null + char dec_buf[5]; + snprintf(dec_buf, sizeof(dec_buf), index != this->offset ? ",%d" : "%d", b); + output_str += dec_buf; break; + } case RawEncoding::ANSI: if (b < 0x20) break;