Question

The problem I'm getting is that I'm getting heap corruption messages during deletion of binary tree nodes. The message says:

HEAP[lab4.exe]: HEAP: Free Heap block 5788c0 modified at 5788e8 after it was freed Windows has triggered a breakpoint in lab4.exe.

This may be due to a corruption of the heap, which indicates a bug in lab4.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while lab4.exe has focus.

It sounds like I'm writing to a block of memory that has been freed. Valgrind seems to confirm this with messages like:

Invalid write of size 4
at 0x8049C65:> BinTree::removeTree(BinTree::Node*) (in/net/metis/home2/alexo2/lab4/a.out)
...
==9681== Address 0x402ab50 is 0 bytes inside a block of size 12 free'd
at 0x40054B4: operator delete(void*) (vg_replace_malloc.c:346) by 0x8049C61: BinTree::removeTree(BinTree::Node*) (in /net/metis/home2/alexo2/lab4/a.out)
...

When I trace through the program, the heap corruption messages begin usually in a parent class or base class destructor. I've been trying to trace this but I have no idea where the problem is. I never use delete on these nodes until the destructor.

I suspect the problem has something to do with the way I'm deleting or keeping track of the binary tree. Here's some code I'll post, not sure if it will help with finding a solution.

So, a class object is dynamically allocated and returned by a function. This object is kept track of with pointers until it finally is inserted into the node of a binary tree. At the end of the program when everything is being deleted, the destructor is called:

void BinTree::makeEmpty()
{
    if ( root != NULL ) {
        removeTree( root );
    }
    root = NULL;
}

void BinTree::removeTree( Node *curr )
{
    if ( curr == NULL )
        return;

    removeTree( curr->left );
    removeTree( curr->right );

    delete curr->data;
    delete curr;

    curr->data = NULL;
    curr = NULL;
}

In some function, this is the call that creates and returns the dynamically allocated object:

Item *aMovie = factory.createMovie( code.c_str() );

On only some, not all, of the nodes, when delete curr->data is reached, the destructor of the object it's pointing to is called, then the parent's destructor, and finally the base class destructor (all of them are empty). Sometimes it's in the parent destructor, sometimes the base class destructor that the heap corruption message is shown.

Any suggestions on what the problem might stem from?

Was it helpful?

Solution

This:

delete curr->data;
delete curr;

curr->data = NULL;
curr = NULL;

is wrong. You shouldn't write to curr->data after you deleted curr. Not even NULL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top