Skip to content
systemcoding.dev
Security

Use-After-Free Bugs Explained With Patterns That Prevent Them

A use-after-free reads or writes memory after free released it. See how it happens in C and C++, how ASan reports it and patterns that stop it.

6 min read
Summarize in AI
Flat illustration of a shield with a lock, a key and a password field, with the C, C++ and OpenSSL logos.

A use-after-free bug happens when a program keeps a pointer to memory that has already been released and later reads or writes through it. The allocator is free to give that memory to someone else, so the stale pointer now aliases a different object. Nothing in the language raises an error, and the result depends on what the allocator did in between. Use-after-free is one of the most common sources of exploitable bugs in C and C++ programs, because an attacker who can control what gets allocated into the freed slot controls what the stale pointer sees. This post shows the bug, the report that exposes it, the shapes it takes in real code and the ownership patterns that remove it. Examples target GCC 15 and Clang 20 on Linux 6.12 with glibc 2.41.

The smallest example

uaf.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct session {
    int  admin;
    char user[28];
};

int main(void)
{
    struct session *s = malloc(sizeof *s);
    s->admin = 0;
    strcpy(s->user, "guest");
    free(s);

    struct session *t = malloc(sizeof *t);   /* often the same block */
    t->admin = 1;
    strcpy(t->user, "root");

    printf("%s admin=%d\n", s->user, s->admin);   /* stale pointer */
    free(t);
    return 0;
}

After free(s), glibc places the 32-byte chunk in its tcache, a per-thread cache of recently freed blocks. The next malloc of the same size takes it right back, so t usually equals s. The stale reads through s then see the data written through t:

Text
root admin=1

The program shows root and admin=1 even though the variable s was set up as a guest. If the stale pointer had been used for an access check, the bug would be an authorization bypass. The exact output depends on the allocator, which makes this undefined behavior, and the same code on another libc could print guest admin=0 or crash.

How AddressSanitizer reports it

Build with gcc -std=c17 -g -O1 -fsanitize=address -o uaf uaf.c. AddressSanitizer poisons freed memory and keeps it out of circulation for a while in a quarantine, so the reuse in t gets a different block, and the stale read is reported:

Text
=================================================================
==52011==ERROR: AddressSanitizer: heap-use-after-free on address 0x603000000010 at pc 0x55a1c2b4b3f2 bp 0x7ffd6f1b2a90 sp 0x7ffd6f1b2a80
READ of size 5 at 0x603000000010 thread T0
    #0 0x55a1c2b4b3f1 in main uaf.c:21
freed by thread T0 here:
    #0 0x7f0a1b2e7b08 in free
    #1 0x55a1c2b4b2c9 in main uaf.c:14
previously allocated by thread T0 here:
    #0 0x7f0a1b2e7a57 in malloc
    #1 0x55a1c2b4b27e in main uaf.c:11
SUMMARY: AddressSanitizer: heap-use-after-free uaf.c:21 in main

The report has the three facts a fix needs: where the stale access happened, where the block was freed, and where it was allocated. The quarantine size is controlled by the runtime option quarantine_size_mb in ASAN_OPTIONS. Because the quarantine is finite, a bug that needs a long delay between free and use can slip through, which is why fuzzing for hours finds more than a unit test does.

Where it comes from in real code

  1. Two owners. Two data structures hold the same pointer, and one frees it. A cache and a list, or a parent and a callback, are typical.

  2. Free in an error path. A function frees its argument on failure and the caller frees it again, or uses it in its own cleanup. The second case is a double free, covered in the next post.

  3. Iterating while removing. A loop calls free(node) and then reads node->next.

  4. Callbacks and events. An object is destroyed while a queued callback still refers to it.

  5. **realloc moves the block.** Code keeps a pointer into the old block after realloc returned a new address.

  6. Returning a pointer to a local. The stack version, where the frame is gone but the pointer survives. GCC warns with -Wreturn-local-addr, and AddressSanitizer reports stack-use-after-return when you run with ASAN_OPTIONS=detect_stack_use_after_return=1.

  7. C++ container invalidation. A std::vector that reallocates invalidates every iterator, pointer and reference into it, and holding a string_view or span of a temporary std::string that has been destroyed is the same bug with a nicer type.

The loop case deserves its own fix because it is so common:

c
for (struct node *n = head; n != NULL; ) {
    struct node *next = n->next;   /* read before freeing */
    free(n);
    n = next;
}

Patterns that prevent it

Pick one owner

The single most effective rule is to give every allocation exactly one owner, the code responsible for freeing it, and let everything else borrow. Write down in the header comment, or better in the type, who owns what. In C, name functions to show it: session_new and session_free own, while session_get returns a borrowed pointer that must not outlive the owner's lifetime.

Set the pointer to NULL after free

free(p); p = NULL; makes a later dereference crash immediately and predictably on most systems, and it makes a second free(p) a harmless no-op. It does not help when other copies of the pointer exist, but it removes the most common one. A tiny macro or a function taking a void ** can enforce the habit, though the macro form evaluates its argument twice, so keep it simple.

Use reference counting when sharing is real

If two parts of the program truly share an object, count references and free at zero. In C++ that is std::shared_ptr, with std::weak_ptr for non-owning observers that must check whether the object is still alive. In C, a manual count in the struct with retain and release functions works, using C11 atomics when threads share it.

Prefer RAII and unique ownership in C++

std::unique_ptr<T> frees the object when it goes out of scope and cannot be copied, so a second owner does not compile. Containers, std::string and smart pointers release memory in destructors, and a raw delete in application code is a signal to review. The C++ Core Guidelines state the rule as R.11 and R.20 through R.37, which cover raw new and delete, owning pointers and smart pointer use.

Use arenas for grouped lifetimes

Allocate everything that lives for one request from an arena, and release the whole arena at the end. Individual frees disappear, and the bug of freeing one object too early disappears with them. The cost is that nothing is returned until the arena ends, so size it to the unit of work.

Use indexes or generation handles

In long-lived systems, hand out small integer handles with a generation count instead of raw pointers. A lookup compares the generation, and a stale handle fails the check and returns an error. Game engines and kernels use this pattern, and it turns a memory-safety bug into a controlled failure.

Tools to find the bugs you already have

Compile tests with -fsanitize=address, and run fuzzers with it on. Valgrind's Memcheck reports Invalid read of size and Address ... is 0 bytes inside a block of size 32 free'd, and works on unmodified binaries. Static analysis helps too: GCC's -fanalyzer has a -Wanalyzer-use-after-free check that follows paths through a function in C. In production, a quarantine-based allocator such as Scudo, or the sampling GWP-ASan, finds use-after-free in the field at low cost, which a later post in this series describes.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.