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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Sarah
  • 1
  • 1
  • 3
    ***because the pointer is not pointing at the same location anymore right?*** no it is pointing at the same location. You just are not permitted to look. Looking invokes undefined behavior. There is a similar question with a very funny answer. I will try to find it. – drescherjm Mar 26 '21 at 23:06
  • It was this one I was thinking of but its not the same as this situation: [https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – drescherjm Mar 26 '21 at 23:12
  • I like [this](https://stackoverflow.com/questions/56979248/why-does-this-simple-program-result-in-puppies-puppies-puppies-to-the-console) @drescherjm – Quimby Mar 26 '21 at 23:12
  • 1
    Here is a duplicate: [https://stackoverflow.com/questions/37464159/c-pointer-array-is-still-accessible-after-delete-is-called](https://stackoverflow.com/questions/37464159/c-pointer-array-is-still-accessible-after-delete-is-called) – drescherjm Mar 26 '21 at 23:12

1 Answers1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    @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. – Remy Lebeau Mar 26 '21 at 23:32