skip to content

Why does a C++ use-after-free often corrupt unrelated data or crash in different code, instead of failing at the line that used the freed memory?

level: seniorimportance: should knowfreq 45%

answer

  1. freed is not unmapped
  2. the allocator reuses the block
  3. the victim crashes, not the culprit
  4. segfault only on unmapped pages
  5. timing and build flags move it

basics

~20 s

Freed memory usually stays mapped and is soon reused for another object, so a stale write corrupts that object silently. The crash, if any, comes later where the corrupted data is used, typically a segfault or access violation in innocent code.

solid answer

~50 s

`delete` or `free` usually returns a small block to the process's allocator rather than to the operating system, so the address stays mapped and reading or writing it does not trap. The next allocation of a similar size may receive the same block. A stale write through the dangling pointer then overwrites a field of the new, innocent object — a wrong currency in an invoice, a broken length in a string — and nothing fails until that object is used. The eventual crash is a **segmentation fault** (SIGSEGV on Linux, `EXC_BAD_ACCESS` on macOS) or an **access violation** (`0xC0000005` on Windows) only when some corrupted pointer leads into unmapped memory, or an allocator abort when its metadata was hit. The stack trace shows the victim, not the culprit. Because block reuse depends on allocation order, optimisation level and threads, the bug moves or disappears between runs; a reproducible crash often needs a build that poisons freed memory.

code

cpp · 19 lines
cpp
#include <cstdio>

struct Session { int userId; int flags; };
struct Invoice { int amount; int currency; };

Session* current = nullptr;                 // a stale global the bug leaves behind

void logout() { delete current; }           // forgets current = nullptr

void markAdmin() { if (current) current->flags = 1; }   // the bug: writes through a dangling pointer

int main() {
    current = new Session{7, 0};
    logout();
    Invoice* inv = new Invoice{100, 978};   // the allocator may reuse the freed block
    markAdmin();                            // use-after-free write, possibly into *inv
    std::printf("amount=%d currency=%d\n", inv->amount, inv->currency);
    delete inv;
}

go deeper

for a junior

Recall that using freed memory does not reliably crash; it is undefined behaviour that can silently return wrong data.

for a middle

Explain that the allocator keeps freed blocks mapped and reuses them, so a stale write lands in a new, unrelated object.

for a senior

Read a crash dump as evidence about the victim object, reason back to who could hold a stale pointer, and make the failure reproducible with memory poisoning.

for a principal

Decide which builds run with poisoning tools in CI and pre-release so heap corruption is caught at the source instead of debugged from field crash reports.

## Freed memory is still there The C++ heap is managed by an allocator inside the process. When an object is deleted, its block goes back to the allocator's free lists, ready for the next `new` of a suitable size. Small blocks are rarely returned to the operating system, so the virtual address stays **mapped and readable**. The hardware therefore has no reason to fault on the first stale access. A **segmentation fault** (POSIX signal `SIGSEGV`; `EXC_BAD_ACCESS` on macOS) or **access violation** (exception code `0xC0000005` on Windows) is raised only when the processor touches a page that is unmapped or protected. That happens with a dangling pointer only in particular cases: - the allocator did return a large block's pages to the operating system; - the stale read fetched a pointer field that now contains garbage, and the program then dereferences that garbage; - a stack frame was popped and the stale address happens to fall in a guard page (rare). ## How the corruption travels The typical sequence in a long-running program: 1. Object `A` is freed while some code still holds `A*`. 2. Object `B`, of a similar size, is allocated and receives the same block. 3. The stale code writes through `A*`. The write lands in `B` at the offset of the `A` field. 4. Much later, unrelated code uses `B`: a length is wrong, a vtable pointer is overwritten, a string's buffer pointer is garbage. 5. That code crashes or produces wrong output. Its stack trace contains no frame from the code that wrote through `A*`. | What the stale write hit | Symptom, later and elsewhere | |---|---| | an integer field of another object | silently wrong data, no crash | | a pointer field of another object | crash when that pointer is followed | | a vtable pointer | crash or wrong function on the next virtual call | | allocator free-list metadata | abort or crash inside a later `new` or `delete` | ## Why it moves between runs Which object receives the freed block depends on allocation order, block sizes, allocator version and thread interleaving. Changing the optimisation level changes allocation patterns and which values stay in registers, so the bug may vanish in a debug build, appear under load, or disappear when logging is added. This is the classic "heisenbug" profile, and it is a direct consequence of the access being **undefined behaviour**: nothing obliges the program to fail where the mistake is. ## The stack has the same property Dangling pointers into the stack behave the same way. When a function returns, its frame is not unmapped: the next call reuses the same addresses for its own locals. A pointer to a dead local therefore reads whatever the next function stored there, and a write through it corrupts that function's variables. In the worst case it overwrites a saved register or a return address, and the crash happens when an unrelated function returns, with a stack trace that may itself be corrupted. Again, the fault appears long after, and far from, the faulty access. ## Making the bug fail at the source The general strategy is to stop freed memory from looking valid: - tools that **poison** freed blocks and keep them out of circulation for a while, so a stale access hits recognisable or inaccessible memory; AddressSanitizer is the standard example, covered with the compiler's sanitizer options; - debug heaps that fill freed blocks with a fixed pattern, so a corrupted field shows that pattern in the crash dump; - hardware watchpoints in a debugger on the corrupted field, to catch the write in the act. Reading the crash dump the right way also matters: treat the crashing frame as evidence about *which object* was corrupted, then ask which code could hold a stale pointer of the size and layout that would write to that offset. ## Interview framing - Say "the crash site is the victim, not the culprit". - Explain mapped versus unmapped memory and why a stale access usually does not trap. - Name the reuse mechanism: the allocator hands the freed block to the next object. - Mention how you would turn the silent corruption into an immediate, attributed failure.

  • Why might the bug disappear when you add a log line?
    Logging allocates and frees its own buffers, which changes which block the allocator hands out next. The freed object's block may now go to the log string instead of the object that used to be corrupted, so the visible symptom moves or vanishes. The use-after-free is still there; only its victim changed.
  • What does it tell you when a crash dump shows a vtable pointer equal to a small integer?
    Something wrote an integer where an object's vtable pointer lives in common ABIs, typical of a stale write through a pointer to a different, freed type that reused the block. The next virtual call jumps through garbage and faults. Look for code that frees objects of that size class while keeping pointers to them.

Mail that keeps arriving after you move out: the new tenant opens your letters and acts on them, and the confusion surfaces at their door, never at the sender's desk where the address went stale.

  • Freed memory is returned to the operating system immediately, so any access traps.
  • The function at the top of the crash stack is where the bug is.
  • If the debug build does not crash, the release build crash is a compiler bug.
  • A use-after-free that only reads cannot cause any harm.
  • Adding a log line fixed it, so the problem was timing, not memory.