Search code examples
c++heap-memorydynamic-memory-allocationdelete-operator

How to debug when program crashes on delete?


When delete executes the program crashes. I tried following code to check for corrupted heap block but if condition results false.

int  rc;
if (_HEAPOK != (rc = _heapchk())) 
{
    switch(rc) 
    {
        case _HEAPEMPTY:
            puts("The heap has not been initialized.");
            break;
        case _HEAPBADNODE:
            puts("A memory node is corrupted or the heap is damaged.");
            break;
        case _HEAPBADBEGIN:
            puts("The heap specified is not valid.");
            break;
    }
}

complete code can be found here: http://cyberkinetica.homeunix.net/os2tk45/xpg4ref/157_L2__heapchkValidateDefa.html

Please let me know how to debug in this case.

EDIT:

I tried to debug in file:

...\Microsoft Visual Studio 9.0\VC\crt\src\dbgheap.c

and it's failing in following function:

extern "C" _CRTIMP int __cdecl _CrtIsValidHeapPointer( const void * pUserData)

Comments on this function states:

Purpose: Verify pointer is not only a valid pointer but also that it is from the 'local' heap. Pointers from another copy of the C runtime (even in the same process) will be caught.

what is this local heap and does it help in finding out the issue?


Solution

  • I assume that you want to know why the code snippet is crashing in your posted link. The problem is in this line.

    *(ptr - 1) = 'x'; // i.e. ptr[-1] = 'x';
    

    After doing ptr = malloc(), you execute above command. Pointer is writing in the memory area which is going out of range; which results in undefined behavior. Luckily the system crashes.