8

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

6
  • 2
    Have you checked the source code for the implementation of std::vector::resize() ? It might do anything from setting errorno to terminating the program. Commented Nov 1 at 21:32
  • 1
    You are right. apparently, lloking to esp-IDF docs "any libstdc++ code which throws an exception will abort instead"... Commented Nov 1 at 21:46
  • 5
    The rule of thumb with vectors and embedded systems is to either avoid std::vector or give it an allocator class, so that memory can be allocated from a memory pool. Commented Nov 2 at 4:29
  • 6
    The better way is just to allocate memory buffer that's big enough for all your runtime use at startup once. You have limited resources so you must "budget" for them anyway, and what better time to check that budget at startup time anyway Commented Nov 2 at 5:53
  • 1
    You have to accept that C++ has exceptions, so disabling them gives you some weird language that only looks similar to C++. If something from C++ doesn't work anymore, you have to write a replacement yourself. Commented Nov 2 at 10:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.