Phil-ZXX
Phil-ZXX

Reputation: 3245

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;
}

Upvotes: 1

Views: 420

Answers (2)

Tomek
Tomek

Reputation: 4659

I would go for reference instead of pointer as parameter:

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

as this would not require client code change. Goswin's proposal requires the call to myReAllocate to be:

myReAllocate(&cc[i]);

while references allow it to be called without a change.

Upvotes: 2

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12322

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();
}

Upvotes: 6

Related Questions