Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) ***
like image 392
rnd_nr_gen Avatar asked Dec 17 '22 20:12

rnd_nr_gen


2 Answers

It is a VERY bad thing to do. However C++ won't necessarily do anything here. It is "un-defined" behaviour. That doesn't mean it will crash but it will, most probably, cause bad shit (tm) to happen.

Edit: Furthermore in your 2nd example the fact it crashes is just a part of "undefined" behaviour. It is undefined as to what the reaction will be.

like image 107
Goz Avatar answered Feb 08 '23 23:02

Goz


Why I did not get error when calling "delete f1"? didn't I delete the same address (*p) twice?

Yes you did delete that object twice.

However, the outcome of that is Undefined Behavior. That could result in the run-time system catching the error and popping up a message, but it could just as well result in your HD getting formatted, nasty Nasal Demons chasing you around the office to the delight of your fellow-workers, or you or your girlfriend getting pregnant. Or then it might also appear to "work", whatever that means in this case.

like image 24
sbi Avatar answered Feb 08 '23 22:02

sbi