multiple C++ deletion of a memory pointed by multiple objects

Posted by elgcom on Stack Overflow See other posts from Stack Overflow or by elgcom
Published on 2010-10-15T09:32:00Z Indexed on 2011/01/13 9:53 UTC
Read the original article Hit count: 224

Filed under:
|
|

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) ***

© Stack Overflow or respective owner

Related posts about c++

Related posts about memory