What is a dangling pointer, and how does modern C++ (C++11 and later) provide tools to avoid them?
Last updated
A dangling pointer is one that still holds an address whose underlying object has already been destroyed or freed, so dereferencing it is undefined behavior. Modern C++ reduces them by encoding ownership and lifetime in types like smart pointers rather than relying on manual delete.
How they arise: Using a pointer after
delete, returning the address of a local, or keeping a pointer into a container that reallocated.RAII smart pointers:
std::unique_ptrandstd::shared_ptrtie deletion to scope/refcount, so you don't leave a raw pointer to freed memory.Observing without owning:
std::weak_ptrlets you check if ashared_ptr-managed object is still alive vialock()before use.Move semantics: Moving a
unique_ptrnulls the source, avoiding two owners that could double-free.Still your responsibility: Smart pointers don't fix dangling raw references or iterators; tools like sanitizers (ASan) catch those at runtime.
- https://www.geeksforgeeks.org/cpp/dangling-pointers-in-cpp/
- https://www.interviewbit.com/pwc-interview-questions/
- https://github.com/Devinterview-io/cpp-interview-questions
- https://www.compilersutra.com/docs/mcq/interview_question/intermediate/memory-management/
- https://github.com/Nabagata/interview-prep
- https://github.com/satyajeetramnit/oops-for-humans
- https://www.compilersutra.com/docs/mcq/interview_question/basic/pointers-references/