Skip to content

Dangling pointer

Category: Hazards · Status: stub · Lessons: chapter 01, Threads

One line: A pointer or reference to storage whose lifetime has ended — the classic way for a thread to outlive the stack frame it was reading.

Also called: use after free, use after return, use after scope.

How it connects

flowchart LR
  n_dangling_pointer["Dangling pointer"]
  n_escape_analysis["Escape analysis"]
  n_safety_failure["Safety failure"]
  n_scoped_thread["Scoped thread"]
  n_undefined_behaviour["Undefined behaviour"]
  n_dangling_pointer -->|can cause| n_undefined_behaviour
  n_dangling_pointer -->|is a| n_safety_failure
  n_escape_analysis -->|prevents| n_dangling_pointer
  n_scoped_thread -->|prevents| n_dangling_pointer
  classDef center stroke-width:3px
  class n_dangling_pointer center
  classDef outside stroke-dasharray: 4 3
  class n_escape_analysis,n_safety_failure,n_scoped_thread,n_undefined_behaviour outside

In each language

Rust Rejected in safe code: the borrow checker requires a reference to be outlived by what it points at
C Lifetime ↗: using a pointer to an object whose lifetime has ended is undefined
C++ Lifetime ↗; a dangling std::string_view ↗ or captured reference is the common form

Where to read more