+ 3

After freeing up the memory used by a pointer, printing the value it points to yields a seemingly random number. Why?

Supposing I do this: cout << *p << endl; delete *p; And because of previously declared statements, this yields: 5 But supposing I do this: cout << *p << endl; delete *p; cout << *p << endl; The compiler outputs something like this: 5 1715714 I would have expected the following: 5 0 Or perhaps 5 NULL Please explain.

24th Apr 2018, 1:21 PM
Anis Ali Khan
Anis Ali Khan - avatar
5 Answers
+ 3
Another question might be "Why would the device bother zeroing or nulling every piece of memory freed up?" Doing so would take time. Once it's free, it can be used by other processes.
24th Apr 2018, 1:25 PM
Emma
+ 2
Note, it should be: delete p; Not delete *p; https://code.sololearn.com/cX73w25r0Vsb/#cpp
24th Apr 2018, 1:38 PM
Emma
+ 2
Yes, exactly. Even if you did zero it before deleting, you have no authority on that bit of memory any more. Other processes can do what they like to it (if they themselves have control over it).
24th Apr 2018, 1:40 PM
Emma
+ 1
Oh I see. I guess that makes sense, once another process initializes or writes to that memory location it makes no difference if it’s been zeroed or not right?
24th Apr 2018, 1:33 PM
Anis Ali Khan
Anis Ali Khan - avatar
+ 1
Thank you
24th Apr 2018, 1:38 PM
Anis Ali Khan
Anis Ali Khan - avatar