Use-After-Free (CWE-416)
A use-after-free (UAF) is an access through a pointer to memory that has already been freed. The pointer still holds the old address (it dangles), and nothing in C stops you from using it. For a while the old bytes may still be there and the program seems fine. Then the allocator hands the same block to a new object, as it does by design, and the dangling pointer now reads and writes that object through the old type. UAF bugs are the largest single class of serious memory bugs in browsers (about half of Chrome's high-severity memory-safety bugs), where JavaScript can free and reallocate objects at will, and they are a large share of the bugs exploited in the wild. They break temporal safety: the access is in the right place at the wrong time.
The bug in a toy program
The toy keeps a struct session for a logged-in user. On logout the session is freed, but one code path still holds the pointer. The very next allocation of the same size is a 20-byte note supplied by a user, and the dangling pointer is then used to make a permission decision:
cat > uaf.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct session { char user[16]; int is_admin; };
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
struct session *s = malloc(sizeof *s);
strcpy(s->user, "alice");
s->is_admin = 0;
free(s); /* logout */
char *note = malloc(sizeof(struct session)); /* next request: a 20-byte note from the user */
memcpy(note, "AAAAAAAAAAAAAAAA\x01\x00\x00\x00", 20);
if (s->is_admin) /* BUG: s is dangling */
printf("dangling session says: admin!\n");
else
printf("dangling session says: not admin\n");
free(note);
return 0;
}
SRC
gcc -g -O0 uaf.c -o uaf && ./uaf
echo "== with ASan"
gcc -g -O0 -fsanitize=address uaf.c -o uaf-asan
./uaf-asan 2>&1 | grep -E 'ERROR|READ|#0 .*uaf.c|located|freed by|previously|^=>'
echo "exit code: ${PIPESTATUS[0]}"
./uaf-asan 2>&1 | grep -E '#1 .*uaf.c'dangling session says: admin!
== with ASan
==21==ERROR: AddressSanitizer: heap-use-after-free on address 0x503000000050 at pc 0x6365c6ad43d6 bp 0x7ffe1952ded0 sp 0x7ffe1952dec0
READ of size 4 at 0x503000000050 thread T0
#0 0x6365c6ad43d5 in main /home/learner/uaf.c:17
0x503000000050 is located 16 bytes inside of 20-byte region [0x503000000040,0x503000000054)
freed by thread T0 here:
previously allocated by thread T0 here:
=>0x503000000000: fa fa 00 00 00 fa fa fa fd fd[fd]fa fa fa 00 00
exit code: 1
#1 0x5fcf7e65b371 in main /home/learner/uaf.c:12
#1 0x5fcf7e65b300 in main /home/learner/uaf.c:9
In the plain build the note got the session's old block (the tcache returns the last freed chunk of that size first), so s->is_admin reads bytes 16–19 of the note, 01 00 00 00, and the logged-out session "becomes" an administrator. No crash, no warning. This is the essence of UAF exploitation: the attacker doesn't overflow anything, they arrange for data they control to occupy the freed object, and the program's own stale pointer does the rest. With an object that contains a function pointer or a C++ vtable pointer, the same trick redirects a call instead of flipping a flag. The toy stops at the flag.
The report, line by line
heap-use-after-free … READ of size 4: a 4-byte load (theint is_admin) from freed memory.#0 main uaf.c:17: theif (s->is_admin).16 bytes inside of 20-byte region:is_adminis at offset 16 of the 20-byte struct.freed by thread T0 hereandpreviously allocated by thread T0 here, with their#1frames printed separately below: freed atuaf.c:12(the logout), allocated atuaf.c:9. Three stacks (use, free, allocation) are what make UAF bugs debuggable; without them you only see the use.fd fd[fd]: "freed heap region". Under ASan the note did not get the old block: ASan keeps freed blocks in a quarantine (256 MB by default) and hands out fresh memory instead, precisely so that dangling accesses hit poisoned bytes.
Root cause
Two pointers refer to one object, and only one of them was told the object is gone. Real UAFs hide the second pointer better: a callback registered with an event loop, an iterator into a container that was resized, a cached pointer in another object, an error path that frees and then falls through into the normal path. The question to ask in review is always "who owns this object, and who else holds a pointer to it?"
The fix
Fix the ownership, not the symptom. Three layers, from weakest to strongest:
- Clear the pointer at the free (
free(s); s = NULL;). A later use becomes a NULL dereference: a clean crash instead of silent corruption. This catches only uses through this variable, not copies of it. - Make one owner responsible, and give everyone else a way to know the object is gone: a session table looked up by an ID on every use, reference counting, or a generation counter that invalidates old handles.
- Let the language enforce it: in C++,
std::unique_ptr/std::shared_ptr+std::weak_ptr; in Rust, the borrow checker rejects this program at compile time (Rust: Ownership, unsafe, FFI and Migration).
The second fix in plain C: sessions are looked up by ID, and logout invalidates the ID, so a stale reference turns into "no such session":
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct session { char user[16]; int is_admin; };
#define MAX_SESSIONS 4
static struct session *table[MAX_SESSIONS]; /* the single owner */
static int login(const char *user, int admin) {
for (int id = 0; id < MAX_SESSIONS; id++)
if (!table[id]) {
table[id] = calloc(1, sizeof(struct session));
snprintf(table[id]->user, sizeof table[id]->user, "%s", user);
table[id]->is_admin = admin;
return id;
}
return -1;
}
static void logout(int id) { free(table[id]); table[id] = NULL; }
static struct session *lookup(int id) { return (id >= 0 && id < MAX_SESSIONS) ? table[id] : NULL; }
int main(void) {
int id = login("alice", 0); /* callers keep the id, never the pointer */
logout(id);
char *note = malloc(sizeof(struct session)); /* the same reallocation as before */
memcpy(note, "AAAAAAAAAAAAAAAA\x01\x00\x00\x00", 20);
struct session *s = lookup(id);
printf("session %d after logout: %s\n", id, s ? (s->is_admin ? "admin" : "user") : "no such session");
free(note);
return 0;
}session 0 after logout: no such session
The note still reuses the old block, but nothing points at it as a session any more: the only path to a session goes through the table, and logout removed the entry. (A production version would add a generation number to the ID so that a new session in slot 0 isn't mistaken for the old one.)
How use-after-free is detected
- ASan with its quarantine; for long-running programs raise
ASAN_OPTIONS=quarantine_size_mb=…so blocks stay poisoned longer. - Fuzzing that exercises lifecycles: open, close, use; add, remove, iterate.
- Static analysis: Clang's static analyzer (
unix.Mallocchecker) and CodeQL find simple "use after free in the same function" paths; cross-function ones need sanitizers. - Mitigations that make UAF harder to exploit: allocators that delay reuse or separate objects by type (Chrome's PartitionAlloc and MiraclePtr, which keep freed memory quarantined while
raw_ptr<T>fields still refer to it; Apple's type-segregated kernel allocatorkalloc_type), and memory tagging, which gives a reallocated block a new tag (Memory Tagging and Hardened Allocators).
The CWE
CWE-416: Use After Free. Related: CWE-825 (Expired Pointer Dereference), CWE-415 (Double Free, the next lesson), and CWE-562 (Return of Stack Variable Address), the stack version of the same mistake.
Pitfalls
free(p); p = NULL;everywhere gives a false sense of safety: copies ofpin other structures still dangle.- Iterator invalidation in C++:
for (auto &x : v) if (…) v.push_back(…);uses references into a vector that may have reallocated. ASan reports it asheap-use-after-free. - Returning pointers to locals (
return buf;wherebufis a local array): ASan catches it withdetect_stack_use_after_return=1.
Practice
1. Why did the plain build see is_admin = 1?
The note was allocated with the same size right after the free, so the tcache returned the session's old block. Bytes 16–19 of the note (01 00 00 00) are where is_admin used to be, and little-endian 01 00 00 00 is 1.
2. Why did ASan's build not reuse the block for the note?
ASan's allocator puts freed blocks in a quarantine and doesn't hand them out again for a while, so dangling accesses hit memory marked fd (freed) and are reported.
3. In the session-table fix, what bug appears if slot 0 is reused by a new login before the stale ID is looked up?
The stale ID would find the new user's session: an authorisation bug, not a memory bug. A generation counter stored in both the ID and the table entry (id = slot | gen << 8) detects it.
Test yourself
What made the logged-out session read as admin in the plain build?
- An overflow of the note
- The allocator reused the freed block for the note, and the dangling pointer read the note's bytes as is_admin
- ASLR
- A compiler bug
Which three stacks does an ASan use-after-free report give?
- Use, free and allocation
- Only the use
- Use and return
- Allocation only
Why does setting the pointer to NULL after free not fully fix use-after-free?
- NULL is not a valid pointer
- Other copies of the pointer elsewhere in the program still dangle
- free ignores NULL
- It is slower
Which memory-safety property does UAF break?
- Spatial
- Temporal
- Type
- Initialisation