Pointers & Memory · advanced · ~8 min

Dangling pointers

Recognize pointers whose target storage has gone away.

Lesson

A dangling pointer is one whose target has been deallocated or has gone out of scope. Two common sources:

  1. Returning a pointer to a local variable from a function.
  2. Holding a pointer to a heap allocation that some other code path has freed.

Both lead to use-after-free style bugs. The compiler can sometimes warn (-Wreturn-local-addr); AddressSanitizer catches the rest at runtime.

Code examples

// BAD
int *bad(void) {
    int x = 42;
    return &x;   // x dies at return
}

Common mistakes

  • Returning the address of a local — the storage is gone immediately.
  • Storing a pointer to a temporary T inside a for loop body.