From bce9041f1f47735ab28faf2fde2fb57ca74fde97 Mon Sep 17 00:00:00 2001 From: Niklas Jensen Date: Fri, 30 Jan 2026 19:04:35 +0100 Subject: [PATCH] Allocate stateful persistance on heap - not stack --- .../template/stateful_persistence_pb.h | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/esp32/include/template/stateful_persistence_pb.h b/esp32/include/template/stateful_persistence_pb.h index 1559b6f..7d3525e 100644 --- a/esp32/include/template/stateful_persistence_pb.h +++ b/esp32/include/template/stateful_persistence_pb.h @@ -46,15 +46,19 @@ class FSPersistencePB { file.close(); if (bytesRead == fileSize) { - T protoMsg = {}; + // Allocate on heap to avoid stack overflow with large proto messages + T *protoMsg = new T(); + *protoMsg = {}; pb_istream_t stream = pb_istream_from_buffer(buffer, bytesRead); - if (pb_decode(&stream, _msgDescriptor, &protoMsg)) { + if (pb_decode(&stream, _msgDescriptor, protoMsg)) { _statefulService->updateWithoutPropagation( - [this, &protoMsg](T &state) { return _stateUpdater(protoMsg, state); }); + [this, protoMsg](T &state) { return _stateUpdater(*protoMsg, state); }); + delete protoMsg; delete[] buffer; return; } + delete protoMsg; } delete[] buffer; } else { @@ -70,10 +74,13 @@ class FSPersistencePB { uint8_t *buffer = new uint8_t[_maxSize]; pb_ostream_t stream = pb_ostream_from_buffer(buffer, _maxSize); - T protoMsg = {}; - _statefulService->read([this, &protoMsg](const T &state) { _stateReader(state, protoMsg); }); + // Allocate on heap to avoid stack overflow with large proto messages + T *protoMsg = new T(); + *protoMsg = {}; + _statefulService->read([this, protoMsg](const T &state) { _stateReader(state, *protoMsg); }); - bool encodeSuccess = pb_encode(&stream, _msgDescriptor, &protoMsg); + bool encodeSuccess = pb_encode(&stream, _msgDescriptor, protoMsg); + delete protoMsg; if (!encodeSuccess) { delete[] buffer;