Peter
Peter

Reputation: 311

Deleted pointer still pointing the old data

I thought the memory where the deleted pointer pointed should be covered with zeros.(not sure ) But it still pointing the int value 10 and same address. What's going on?

int *p = new int;
*p = 10;
cout << *p << endl; //10
cout << p << endl;  //0x7fafc3c02e80    
delete p;
cout << *p << endl; //10
cout << &(*p) << endl;  //0x7fafc3c02e80!
return 0;

Upvotes: 0

Views: 131

Answers (3)

infixed
infixed

Reputation: 1155

You have returned the space that was allocated to the free heap pool. That does not mean something is going to write zeros to it. That takes time, and you might not want to spend that time on that task.

I suppose some types could have destructors that could clear their storage during destruction, but an int doesn't.

If you do want data erased, clear it yourself before calling delete

It's also a bad idea to continue to use the memory after you've told the system you are done with it.

So you have the option of setting your pointer to NULL after the delete, that will help cause an exception if you do screw up and try to use the old pointer.

Upvotes: 1

Khalil Khalaf
Khalil Khalaf

Reputation: 9407

You are not deleting the actual value of the pointer or the value its pointing at. You are just deallocating the memory so some other pointer "later" will be able to point at that same spot.

Upvotes: 0

Tim Rutter
Tim Rutter

Reputation: 4679

The delete operator frees the memory that was pointed to by the pointer. Once free it can be reallocated at any time so accessing that pointer will have unpredictable results. In your program it is simply the case that the memory has not yet been reallocated for anything else.

https://msdn.microsoft.com/en-us/library/h6227113.aspx

Specifically:

"Using the delete operator on an object deallocates its memory. A program that dereferences a pointer after the object is deleted can have unpredictable results or crash. When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor)."

Upvotes: 2

Related Questions