Skip to main content

Command Palette

Search for a command to run...

dangling pointer

Published
2 min readView as Markdown

A dangling pointer is a pointer that points to memory which has been freed or deleted.
That means — the memory no longer exists or is invalid, but the pointer still holds its old address.


⚙️ How it happens:

There are 3 common cases where dangling pointers are created:

1️⃣ When a local variable goes out of scope

#include <iostream>
using namespace std;

int* fun() {
    int x = 10;   // local variable
    return &x;    // returning address of local variable ❌
}

int main() {
    int* ptr = fun();  // ptr points to memory that no longer exists
    cout << *ptr << endl;  // ❌ Undefined behavior
    return 0;
}

Why dangling?
x is destroyed when fun() ends, but ptr still holds its address.


2️⃣ After deleting a pointer

#include <iostream>
using namespace std;

int main() {
    int* p = new int(5);
    delete p;      // memory freed
    cout << *p;    // ❌ Dangling pointer - accessing deleted memory
    return 0;
}

Fix:
After deleting, always set pointer to nullptr.

delete p;
p = nullptr;

3️⃣ When an object is deleted

#include <iostream>
using namespace std;

class Test {
public:
    void show() { cout << "Hello"; }
};

int main() {
    Test* t = new Test();
    delete t;     // object deleted
    t->show();    // ❌ Dangling pointer
}

⚠️ Problems Caused by Dangling Pointers

  • Program crashes

  • Undefined behavior

  • Security risks (can point to sensitive or random data)


How to Avoid Dangling Pointers

  1. Initialize pointers to nullptr

     int* p = nullptr;
    
  2. After deleting, set pointer to nullptr

     delete p;
     p = nullptr;
    
  3. Avoid returning addresses of local variables

  4. Use smart pointers (unique_ptr, shared_ptr) — they automatically manage memory.

More from this blog

Amit singh's blog

235 posts