Pointers & Memory · advanced · ~8 min

Dangling pointers

Distinguish an out-of-bounds pointer from a pointer whose target has expired.

Overview

A dangling pointer refers to an object whose lifetime has ended. This can happen after free or after leaving the block of an automatic local object. Being inside a numeric address range is not enough: the object must also still be alive.

Core concepts

A function must not return the address of its automatic local variable for later use. To return data safely, return a value, fill caller-owned storage, or return a new owned allocation with documented cleanup.

A pointer into a live array is borrowed. Check an index before forming the element pointer, and keep the source object alive while using the result. Bounds and lifetime are independent checks: an in-range index cannot rescue a freed source.

The linked exercises practice bounds checking as one part of pointer validity. They do not detect expired objects or prove general memory safety.

Lesson

A dangling pointer refers to an object whose lifetime has ended. This can happen after free or after leaving the block of an automatic local object. Being inside a numeric address range is not enough: the object must also still be alive.

Code examples

#include <stdio.h>
void make_value(int *out) { *out = 8; }
int main(void) {
    int result = 0;
    make_value(&result);
    printf("%d\n", result);
    return 0;
}

Expected output on a successful allocation, where applicable:

8

Line by line

The caller owns result and keeps it alive while make_value writes to it. No pointer to a callee-local variable escapes its block.

Practice tasks

  1. Explain why returning &local from a function cannot replace this output-parameter approach.
  2. Solve Is an index in bounds?.
  3. Solve Bounds-checked element pointer.
  4. State the extra lifetime obligation that remains after a bounds check succeeds.

Summary

Check lifetime as well as bounds. A returned borrowed pointer requires a live owner. Prefer returning values or writing caller-owned storage when an allocation is unnecessary.

Practice with these exercises