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) ***
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With