Back to results for “Memory Management”
C++ › Memory Management

What is a dangling pointer and how does it arise?

Intermediate

Answer

A dangling pointer points to memory that has been freed or gone out of scope, so dereferencing it is undefined behavior. It arises from using a pointer after delete, returning the address of a local variable, or holding a pointer/iterator into a container after it reallocates. Setting freed pointers to nullptr and using smart pointers reduces the risk.
int* p = new int(5);
delete p;
*p = 10;   // dangling: undefined behavior
Real-world example A cached raw pointer crashes the app after the object it referenced was destroyed.

Common follow-ups: How do you avoid dangling pointers? | What is use-after-free?