Advertisement
Intermediate C++, Memory Management

What is a dangling pointer and how does it arise?

Short 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.

Save C++ mock interview
Advertisement
AModel 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.
Likely follow-ups
  • How do you avoid dangling pointers? | What is use-after-free?
Related topics