Search code examples
c++memory-management

Heap corruption: What could the cause be?


I am investigating a crash due to heap corruption. As this issue is non-trivial and involves analyzing the stack and dump results, I have decided to do a code review of files related to the crash.

To be frank, I don't have in-depth knowledge of when the heap could be corrupted.

I would appreciate if you could suggest scenarios which could lead to heap corruption.

Platform: Windows XP

Language: C++

Compiler: VC6


Solution

  • Common scenarios include:

    • Writing outside the allocated space of an array (char *stuff = new char[10]; stuff[10] = 3;)
    • Casting to the wrong type
    • Uninitialized pointers
    • Typo error for -> and .
    • Typo error when using * and & (or multiple of either)

    [EDIT] From the comments, a few more:

    • Mixing new [] and new with delete [] and delete
    • Missing or incorrect copy-constructors
    • Pointer pointing to garbage
    • Calling delete multiple times on the same data
    • Polymorphic baseclasses without virtual destructors