A C++ book I have been reading states that when a pointer is deleted using the delete
operator the memory at the location it is pointing to is "freed" and it can be overwritten. It also states that the pointer will continue to point to the same location until it is reassigned or set to NULL
.
In Visual Studio 2012 however; this doesn't seem to be the case!
Example:
#include <iostream>
using namespace std;
int main()
{
int* ptr = new int;
cout << "ptr = " << ptr << endl;
delete ptr;
cout << "ptr = " << ptr << endl;
system("pause");
return 0;
}
When I compile and run this program I get the following output:
ptr = 0050BC10
ptr = 00008123
Press any key to continue....
Clearly the address that the pointer is pointing to changes when delete is called!
Why is this happening? Does this have something to do with Visual Studio specifically?
And if delete can change the address it is pointing to anyways, why wouldn't delete automatically set the pointer to NULL
instead of some random address?
cout
, what is the value of the pointer when viewed in the debugger? The reason why this is important is that you are running the pointer through the gauntlet ofoperator <<
. Who knows what will come out at the other end if the pointer is no longer valid. – Erasure0x00008123
, the answer is "It doesn't matter". Firstly, it's non-portable to expect a compiler to do so, and secondly, the value written is also an "invalid pointer value" and illegal to read. It's illegal to read not because it is an "indeterminate value" (which might not be true after the compiler writes to it), but by virtue of containing an "invalid pointer value". – Lashio0x00008123
" is a legal result of undefined-behavior. Although, strictly speaking, reading an "invalid pointer value" is implementation-defined behavior according to the Standard (but a footnote is pretty clear that an implementation can specify any behavior, including what we normally associate with undefined behavior) – LashioNULL
:ptr = NULL
, then print it's value.cout << ptr << endl;
. You will find that when a pointer is explicitly set toNULL
it will point to the address00000000
... – Comply