I'm working in an ESPHome / embedded C++ environment, where exceptions are disabled, so std::vector::resize() won't throw std::bad_alloc on allocation failure.
I need to resize a std::vector to match a payload size from a frame header, and I want to detect if memory allocation failed (to set an error code like FPC_RESULT_OUT_OF_MEMORY).
Here’s the simplified code:
if (result == FPC_RESULT_OK) {
frame_payload.resize(frame_hdr.payload_size);
if (frame_payload.capacity() < frame_hdr.payload_size) {
ESP_LOGE(TAG, "Failed to allocate memory for frame payload");
result = FPC_RESULT_OUT_OF_MEMORY;
}
}
Apparently, looking at esp-IDF docs
"any libstdc++ code which throws an exception will abort instead"
, so the real question is:
- How can I modify this code without aborting the whole program if the allocation goes badly?
Environment:
- ESPHome / ESP-IDF
-fno-exceptions- C++17
std::vector::resize()? It might do anything from settingerrornoto terminating the program.std::vectoror give it an allocator class, so that memory can be allocated from a memory pool.