From a92a08c2de7736369f533679b0685e07ad59d990 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 28 Aug 2025 13:40:36 -0500 Subject: [PATCH] [api] Fix string lifetime issue in fill_and_encode_entity_info for dynamic object_id (#10482) --- esphome/components/api/api_connection.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/esphome/components/api/api_connection.h b/esphome/components/api/api_connection.h index 6254854238..72254d1536 100644 --- a/esphome/components/api/api_connection.h +++ b/esphome/components/api/api_connection.h @@ -303,11 +303,13 @@ class APIConnection final : public APIServerConnection { msg.key = entity->get_object_id_hash(); // Try to use static reference first to avoid allocation StringRef static_ref = entity->get_object_id_ref_for_api_(); + // Store dynamic string outside the if-else to maintain lifetime + std::string object_id; if (!static_ref.empty()) { msg.set_object_id(static_ref); } else { // Dynamic case - need to allocate - std::string object_id = entity->get_object_id(); + object_id = entity->get_object_id(); msg.set_object_id(StringRef(object_id)); }