In a case of a heap corruption, can new
throw?
If I understand it correctly, in a case of a heap corruption, all bets are off, and anything can happen. Is this correct?
Common sources. Some of the most common sources of heap corruption include: a memory assignment that corrupts the header of an allocated block. an incorrect argument that's passed to a memory allocation function.
Check for heap corruption Most memory corruption is actually due to heap corruption. Try using the Global Flags Utility (gflags.exe) or pageheap.exe. See /windows-hardware/drivers/debugger/gflags-and-pageheap.
Yes, if the heap is corrupted, anything can happen. Throwing an exception is possible, but unlikely. What's more likely is that it will start trashing memory; if you're lucky, you'll just get a GPF/Segmentation fault. If you're unlucky, your program will continue running with a corrupt heap.
( Moved from a comment to an answer at Als' suggestion, and extended for better or worse :-) )
A corrupted heap invalidates any behavioural expectations you may have of the program. Crucially, throwing an exception implies some reliable programmatic handling is possible, but no implementation detecting heap corruption could possibly know whether that's true or not, therefore they're much more likely to assert
or similar.
If we consider what types of corruption a heap may have:
Corrupt records related to the current state of the heap.
new
/new[]
/delete
/delete[]
/malloc
/realloc
/free
loops infinitely etc..new[]
: corruption implies delete[] will destruct the wrong number of elements. If the number is reduced, some objects won't be destructed, potentially causing leaks of memory they contained pointers to, failure to decrement reference counters, file handles left open, mutexes left locked, shared memory segments not destroyed etc.. If the number increases, delete[]
is likely to access past the memory containing the array - possibly causing SIGSEGV - calling destructors equivalent to a reintrepet_cast<>
of the memory content as the object to be destroyed. That might try to dereference/delete/free invalid pointers, close "random" file handles etc..Application data
new
and new[]
may be damaged, corrupting the program state, pointers and handles they contain etc.. Problems could manifest in any number of ways.More generally regarding the heap, at very best you can hope that new will throw when heap is exhausted, but even that's far from guaranteed - particularly on O.S.s where only virtual memory is allocated by new
, and if later page faults can't be satisfied they manifest as SIGSEGV or similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With