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?