Given this little piece of code :
#include <iostream>
#include <assert.h>
using namespace std;
struct Foo
{
// something
};
int main()
{
Foo *p1 = new Foo;
Foo * p2 = p1;
assert(NULL != p1);
delete p1;
p1 = NULL;
assert(NULL != p2);
delete p2;
cout << "everything is cool!" << endl;
return 0;
}
When I delete p1 , the second assert (assert(NULL != p2);) is not failing , why ?
The output : everything is cool!
Then why the assert of p2 is not failing ?
Watch the stars, in particular.
You’re right to suspect that everything is not cool. The program invokes the delete operator twice on the same object (a “double free” error), which will tend to corrupt the heap. If the program continued, you would see undefined behavior at some point. Having undefined behavior rather defeats the point of writing a computer program. If you want to see errors like this immediately and unambiguously, run it under valgrind’s memcheck or equivalent.