Pointers & Memory · advanced · ~10 min

Use-after-free

Understand a vulnerability class central to modern exploitation.

Lesson

Using a pointer after free is undefined behaviour — and a popular exploitation primitive. The freed memory may be reused for something else; reading or writing through the stale pointer corrupts unrelated state.

Defensive habits: set pointers to NULL after free (free(p); p = NULL;), and never store a freed pointer in a long-lived structure. Compile with AddressSanitizer in CI — it catches most use-after-free at runtime.

Common mistakes

  • Caching pointers into a data structure that is later freed — the cache now points at garbage.
  • Functions that "return" a pointer into a freed scratch buffer.