What is a dangling pointer, and how does modern C++ (C++11 and later) provide tools to avoid them?

Last updated 21 June 2026

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_ptr and std::shared_ptr tie deletion to scope/refcount, so you don't leave a raw pointer to freed memory.

  • Observing without owning: std::weak_ptr lets you check if a shared_ptr-managed object is still alive via lock() before use.

  • Move semantics: Moving a unique_ptr nulls 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/
All C++ interview questions