How to safely resize a std::vector and detect allocation failure when exceptions are disabled (ESPHome / embedded C++)

2026-05-29

Stack Overflow: View Question

Tags: c++, memory-management, esp-idf

Score: 9 | Views: 246

The asker is working in an ESP-IDF/ESPHome environment where C++ exceptions are disabled at compile time (-fno-exceptions). They need to resize() a std::vector to a size dictated by an untrusted frame header, and recover gracefully if the device doesn't have enough heap to satisfy the request. Normally std::vector::resize() throws std::bad_alloc on failure, but with exceptions off, libstdc++ / libc++ typically calls std::abort() instead — which on an ESP32 means a watchdog reset. Not great for a robust protocol handler.

Why it's tricky: the STL was designed around exceptions for failure signaling. Once you remove that channel, the allocator's failure path becomes a one-way trip to abort. You can't "try" a resize and check a return code, because there is no return code. And you can't catch what was never thrown.

Approaches, roughly in order of cleanliness:

Gotchas: resize() may allocate more than new_size due to capacity growth strategy — call reserve() with exact size first, or use a std::vector with a shrinking strategy. Heap fragmentation on ESP32 means a "successful" pre-flight check can still fail moments later if another task allocates. And PSRAM-backed allocations need MALLOC_CAP_SPIRAM — easy to miss when the default heap is small.

The challenge: The STL's failure-signaling channel is exceptions, so disabling them turns "handle out-of-memory" from a try/catch into an architectural question about who owns the allocation.

All newsletters