Search code examples
c++memory-managementfree

what happens when routine "free" fails in a "try" block in c++


Typically, if memory issue occurred in calling routine "free", a program will stop immediately with error message telling details of the error. Now assume "free" is called in a "try" block. If an error occurred with the call, will the program stop immediately with an error message, or will the program completes execution of the "try" block before exiting with error message?


Solution

  • free can't error out without some preexisting problem in your code occurring, almost certainly a result of undefined behavior. Once you're in the land of nasal demons, there are no guarantees. free doesn't have a concept of exceptions (it's a C function, no C++ features), or even error return codes; if you corrupt your heap, the program is already screwed, and what comes next can be anything. In practice, I'd expect one of four possibilities:

    1. free doesn't notice the corrupted heap, and just makes things worse silently (try block continues running, because it doesn't realize anything is wrong)
    2. free notices the corrupted heap, and the program dies immediately (no try/catch handling)
    3. free is operating on a pointer to an invalid/unallocated region of memory, and you die with a segfault, bus error, etc. (again, no try/catch handling)
    4. The pointer is to allocated memory that's not part of the heap; behaves like #1 or #2 depending on how "heap-like" it happens to look to the code.