multiple C++ deletion of a memory pointed by multiple objects
- by elgcom
Another c++ pointer deletion question is in the following example:
class Foo {
public:
int *p;
~Foo() {
delete p; p = NULL;
}
};
Foo *f1 = new Foo();
Foo *f2 = new Foo();
f1->p = new int(1);
f2->p = f1->p;
delete f2; // ok
delete f1; // no error?
Why I did not get error when calling "delete f1"? didn't I delete the same address (*p) twice?
If I directly delete the pointers in the last 2 lines of code, I will get error.
delete f2->p; // ok
delete f1->p; // error!! *** glibc detected *** double free or corruption (fasttop) ***