Search code examples
c++operator-overloadingheap-memorynew-operatordelete-operator

Heap corruption when using delete/new in extra function


In the following code sample Visual Studio gives me the error "A heap has been corrupted". At first the for-loop seems to work fine, but after 1 or 2 iterations it just crashes.

I feel that my function myReAllocate facilitates some sort of memory leak where it shouldn't (because when I comment it out, everything works fine). What exactly is going on? It seems like a very subtle error.

#include <iostream>
using namespace std;

class myClass{};

void myReAllocate(myClass* c)
{
    delete c;
    c = new myClass();
}

int main(void)
{
    myClass *cc[10];

    for (int i = 0; i < 10; i++){
        cout << i << " attempt" << endl;
        cc[i] = new myClass();
        myReAllocate(cc[i]);
        delete cc[i];
    }

    return 0;
}

I have tried adding a operator= but it didn't help either.

myClass operator=(myClass& right) {
    myClass temp = right;
    return *this;
}

Solution

  • myReAllocate gets the address of the myClass as parameter. You then free that address and allocate a new object and assign it to the local variable. This has no effect on the value of cc[i]. So when you then delete cc[i] you delete the already deleted object again.

    If you want do to something like that then you need to pass the address of cc[i] (or reference to it) so you can change it:

    void myReAllocate(myClass** c)
    {
        delete *c;
        *c = new myClass();
    }