From 6abc2efd961dda4af0332eabd5335453d7cd71d1 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 10 Oct 2025 11:18:57 -1000 Subject: [PATCH] [json] Fix PSRAM allocator dangling pointer crash (#11165) --- esphome/components/json/json_util.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/esphome/components/json/json_util.cpp b/esphome/components/json/json_util.cpp index dbdf6e3486..869d29f92e 100644 --- a/esphome/components/json/json_util.cpp +++ b/esphome/components/json/json_util.cpp @@ -8,6 +8,13 @@ namespace json { static const char *const TAG = "json"; +#ifdef USE_PSRAM +// Global allocator that outlives all JsonDocuments returned by parse_json() +// This prevents dangling pointer issues when JsonDocuments are returned from functions +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) - Must be mutable for ArduinoJson::Allocator +static SpiRamAllocator global_json_allocator; +#endif + std::string build_json(const json_build_t &f) { // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson JsonBuilder builder; @@ -33,8 +40,7 @@ JsonDocument parse_json(const uint8_t *data, size_t len) { return JsonObject(); // return unbound object } #ifdef USE_PSRAM - auto doc_allocator = SpiRamAllocator(); - JsonDocument json_document(&doc_allocator); + JsonDocument json_document(&global_json_allocator); #else JsonDocument json_document; #endif