1

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

2 Answers 2

6

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Your new function works. Thanks! But why is *c local? Isn't it pointing to the cc[i]? Isn't that all I need? And why would a simple void myReAllocate(myClass* c){ delete c; *c = *(new myClass()); } not work?
Because then you delete c while assigning something to it in the next instruction. You write to memory that's already been freed. You also allocate an object that is never ever freed causing memory leaks. If you want (and you realy should) use asignement then drop the delete and new and only do asignment.
What do you mean by only use assignment?
cc[i] = myClass(); There is also std::vector but I assume you are learning about pointers so that might be against the exercise.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.