Walter Savitch's ``Problem Solving With C++, 9th Edition'' states on page 517:
When you apply delete to a pointer variable, the dynamic variable it is pointing to is destroyed. At that point, the value of the pointer variable is undefined, which means that you do not know where it is pointing, nor what the value is where it is pointing. Moreover, if some other pointer variable was pointing to the dynamic variable that was destroyed, then this other pointer variable is also undefined.
However, it seems that under clang-902.0.39.1
, deleting a pointer doesn't impede my ability to use the variable. Here is a short example demonstrating this behavior:
int *p1, *p2;
p1 = new int(3);
p2 = p1;
cout << *p1 << endl << *p2 << endl;
delete p1;
cout << *p1 << endl << *p2 << endl;
Using this code, I have an output of 4 3
s on separate lines. I would expect an error to occur when referencing p1
and p2
after delete p1;
, should I not?
Under Visual Studio's C++ compiler, referencing p2
outputs a large negative number, indicating we are referencing memory that does not belong to us, and accessing p1
causes the program to crash.