Skip to main content

Command Palette

Search for a command to run...

dangling pointer

Published
•2 min read•View as Markdown

⚙️ The Truth: Memory isn’t erased immediately

When you write:

int *p = new int(5);
delete p;
cout << *p;   // still prints 5 😮

This is called undefined behavior —
but “undefined” does not mean it will always crash.
It just means the compiler is free to do anything:

  • Sometimes it prints 5

  • Sometimes it prints garbage

  • Sometimes it crashes

  • Sometimes it does nothing


🧠 Why does it still print 5?

When you do delete p:

  • You tell the system: “this memory is free; you can reuse it later.”

  • But the OS does not immediately erase or overwrite that memory.

  • So, for a short time, the old value (5) still physically exists in RAM.

So when you do:

cout << *p;

You’re still reading from that same memory address —
and since it hasn’t been reused yet, it prints 5.


🔍 Memory Diagram

Before delete:
   Address 1000 → 5
   p = 1000

After delete:
   Address 1000 → marked as "free"
   Value (5) may still exist temporarily
   p = 1000  (dangling)

👉 That’s why you still get 5 — but it’s just luck, not correct behavior.


💥 Why it’s dangerous

Because later:

  • Some other variable or program may reuse that same memory (address 1000).

  • Then *p will read wrong data or even crash.

So, the pointer still points to that memory,
but that memory no longer belongs to you.


🧩 Real-Life Example

Imagine:

  • You have a house (address 1000).

  • You move out and give the house back to the landlord (delete).

  • The old furniture (value = 5) is still there for now.

  • If you sneak back in and look, you might still see it! 😄
    But once someone new moves in, everything changes —
    and you can’t trust that house anymore.

That’s exactly what happens with a dangling pointer.


✅ Safe Way

Always set pointer to NULL (or nullptr) after deleting:

int *p = new int(5);
delete p;
p = NULL;  // or p = nullptr;

if (p != NULL)
    cout << *p;
else
    cout << "Pointer is invalid now";

More from this blog

Amit singh's blog

235 posts