0

What is the diffrence between

{p = NULL ;}

and

{Delete p; }

When I executed this code:

int *p ;
p = new int;
* p = 4;
cout << *p; // = 4
delete p ;
cout << *p; // 

In the last line, I expected to get a garbage value because the pointer is not pointing at the same location anymore, right? But instead I got the same value which is 4, how is this possible?

4

1 Answer 1

1

p = NULL; merely sets p to NULL, but does nothing to the memory that p was pointing at.

delete p; frees the memory that p is pointing at, provided that memory was allocated with new (as it is in your example).

In your example, trying to access *p after calling delete p; is undefined behavior, so anything can happen. p is still pointing at the same address it was before, delete does not alter p itself in any way, but the memory that p is pointing at is no longer valid. You happen to be seeing the old data that was stored in that memory, but only because it simply hasn't been overwritten yet. But it is still not permissible to access invalid memory for any reason. The actual memory be still be physically allocated by the underlying memory manager, but is logically inaccessible to your code, until it is reallocated again.

Sign up to request clarification or add additional context in comments.

1 Comment

@biqarboy In most implementations, delete/free() is unlikely to actually return the memory back to the OS right away, the runtime may hold on to the memory for awhile for a future new/malloc() to reuse. So the memory is not physically deallocated, only logically. The runtime can allocate physical memory in larger chunks and sub-divide it for new/malloc() to use as needed. So in that regard, old data can still be accessed. But once the memory is handed back to the OS, all bets are off as to the behavior of the memory.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.