Use After Free
Use-after-free is reading or writing a block after free. The pointer is dangling. The bytes may now belong to a different allocation. The program is undefined.
Detailed Explanation
The sequence is p = malloc(...); free(p); *p = 1; or printf("%s", p) or p->next. The last form is common in list code that frees a node and then follows next without a copy. The first form is common in error paths that free and then log a field.
Exploiters love this bug. A malloc after the free can place an object of an attacker's choice on those bytes. A write through the old pointer then corrupts the new object — a vtable pointer, a uid, a length. That is why browsers and kernels treat UAF as a security class, not a crash class.
Mitigations in development: AddressSanitizer, Valgrind, quarantine in debug allocators. Mitigations in production: hardened allocators that delay reuse, pointer tagging. None of them replace ownership.
The design fixes are the same as for dangling pointers. Copy next before free. Null the pointer if it is the only copy. Do not keep hash-table entries that point at freed nodes. Do not return a pointer to a buffer you already freed on the error path. After realloc moves, stop using the old pointer.
A related bug is use-after-return (stack UAF). Same idea, different region. ASan catches both with different banners.
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
static void list_free(struct Node *head)
{
while (head != NULL) {
struct Node *next = head->next; /* copy first */
free(head);
head = next;
}
}
int main(void)
{
struct Node *a = malloc(sizeof *a);
struct Node *b = malloc(sizeof *b);
if (a == NULL || b == NULL) {
free(a);
free(b);
return 1;
}
a->value = 1;
a->next = b;
b->value = 2;
b->next = NULL;
list_free(a);
return 0;
}Common Gotchas
`free(p); log(p->name)` is use-after-free
log first, or copy the name.
ASan's "heap-use-after-free" report includes the allocate, free, and use stacks
read all three.
`free(p); p->next` without saving `next` loses the list and is UAF
`free(p); p->next` without saving `next` loses the list and is UAF
A crash in `malloc` long after a `free` is often a UAF or double-free that alrea
A crash in `malloc` long after a `free` is often a UAF or double-free that already corrupted the heap