Skip to main content
Heap Internals, Use-After-Free & tcache Fundamentals
Lesson 6 of 7

Heap Internals, Use-After-Free & tcache Fundamentals

Understand how the glibc ptmalloc2 heap allocator manages chunks and tcache freelists, how Use-After-Free bugs arise from dangling pointers, and how modern allocator hardening and memory-safety practices prevent them.

Expert 38 min Binary exploitation
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Explain the layout of allocated and freed glibc ptmalloc2 heap chunks including size flags and forward pointers
  • Describe how the per-thread tcache speeds up small allocations and enforces double-free and Safe-Linking checks
  • Identify Use-After-Free vulnerabilities caused by dangling pointers and chunk reuse in C programs
  • Inspect live heap chunk metadata and tcache bins in controlled lab binaries using pwndbg
  • Apply defensive coding patterns and sanitizer tooling to eliminate temporal memory corruption bugs

Recommended first: Process Memory Layout, Stack Frames & Heap OverviewExploit Debugging with GDB-pwndbg & pwntoolsReturn-Oriented Programming (ROP) & ret2libc Chains

#Why this matters

Real-world servers, browsers, and parsers manage complex object graphs on the heap. Because heap allocations have dynamic lifetimes controlled by application logic rather than function returns, lifetime mistakes create Use-After-Free (UAF) and double-free bugs. Even with stack canaries and NX enabled, temporal memory errors can corrupt function pointers, object headers, or allocator metadata.

For security engineers, understanding how glibc ptmalloc2 structures chunks and manages tcache freelists is essential for triaging heap crashes and verifying modern allocator mitigations.

#How glibc ptmalloc2 structures a heap chunk

On Linux, malloc() and free() are implemented by ptmalloc2. Each chunk carries an 8-byte size field (plus an 8-byte prev_size field that an allocated chunk borrows from the next chunk's header as its final 8 user bytes), rounded up to a 16-byte boundary on x86-64 with a minimum chunk size of 0x20 (32 bytes).

Because every chunk size is a multiple of 16 bytes, the lowest three bits of size are repurposed as status flags:

Flag bit Name Meaning
0x1 (P) PREV_INUSE The previous contiguous chunk in memory is currently allocated
0x2 (M) IS_MMAPPED The chunk was allocated separately via mmap rather than the heap arena
0x4 (A) NON_MAIN_ARENA The chunk belongs to a secondary thread arena instead of the main arena

malloc() returns a pointer to the user data region, 8 bytes past size. Once passed to free(), ptmalloc2 reuses the first bytes of the former user region for freelist pointers (fd/bk or tcache_entry fields).

  1. Metadataprev_size (8B, shared when prev in use) and size + A/M/P flags (8B)
  2. User Data (when allocated)Application struct fields or string buffer
  3. Freelist Link (when freed)Mangled next pointer (fd) and tcache key

#tcache architecture and Safe-Linking

To avoid arena lock contention in multithreaded programs, glibc (2.26+) places a tcache_perthread_struct at the start of each thread's heap. It tracks 64 singly-linked Last-In, First-Out (LIFO) bins for small chunks from 0x20 to 0x410 bytes on x86-64, holding up to 7 chunks per bin by default.

When a small chunk is freed and its bin has space, ptmalloc2 pushes it onto the tcache head; the next matching malloc() immediately pops it. Modern glibc enforces two key protections on tcache entries:

  1. Double-free detection (key field): Freed tcache chunks store a pointer to tcache_perthread_struct (or a randomized cookie in newer glibc) in their second 8-byte slot. Calling free() twice on the same chunk triggers a bin scan and aborts on match.
  2. Safe-Linking pointer mangling: Since glibc 2.32, tcache and fastbin forward pointers are stored as (chunk_addr >> 12) ^ actual_next_ptr. Mixing the ASLR-randomized heap page address into the link causes blindly overwritten pointers to dereference invalid addresses without a heap leak.
  1. Program calls free(ptr)Check chunk size fits tcache (0x20-0x410)
  2. Validate key fieldAbort if chunk already present in bin
  3. Mangle next pointerApply Safe-Linking XOR with (addr >> 12)
  4. Push to tcache headIncrement bin count (max 7)

#Use-After-Free and chunk reuse mechanics

A Use-After-Free (UAF) occurs when code frees a heap object yet retains a reference to its address -- a dangling pointer. Because free() marks the chunk available without zeroing its contents or invalidating existing pointers, two distinct failure modes emerge:

  • Metadata exposure or corruption: Reading through the dangling pointer after free() exposes the allocator's tcache metadata (such as the mangled fd pointer or key), while writing through it can corrupt the freelist structure.
  • Type confusion via chunk reuse: When another part of the program allocates a new object of the same tcache size class, the allocator hands back the exact address still referenced by the dangling pointer. Operations through the old pointer now interpret the new object's fields under the old type layout.

Consider this simplified C pattern illustrating a dangling pointer alongside its safe remediation:

c
struct Session {
    char username[24];
    void (*log_action)(const char *);
};

void process_session_unsafe(struct Session *s) {
    free(s);
    /* BUG: s is now a dangling pointer; a new allocation of size 0x20
       can reclaim this chunk before the stale reference is used. */
    if (s->log_action != NULL) {
        s->log_action(s->username);
    }
}

void process_session_safe(struct Session **s_ref) {
    if (s_ref == NULL || *s_ref == NULL) {
        return;
    }
    free(*s_ref);
    *s_ref = NULL; /* Clear the pointer immediately after free */
}

In pwndbg, analysts inspect chunk transitions directly in a controlled lab binary using vis_heap_chunks and tcachebins to observe how size rounding, flags, and bin counts evolve across allocations and frees.

Inspecting heap chunks and tcache state in pwndbg
$ gdb -q ./heap_lab
pwndbg> break main
pwndbg> run
pwndbg> vis_heap_chunks 4
0x555555559290	0x0000000000000000	0x0000000000000031	........1.......
0x5555555592a0	0x6161616161616161	0x0000000000000000	aaaaaaaa........
0x5555555592b0	0x0000000000000000	0x0000000000000000	................
0x5555555592c0	0x0000000000000000	0x0000000000020d41	........A.......	 <-- Top chunk
pwndbg> tcachebins
tcachebins
0x30 [  1]: 0x5555555592d0 -> 0x0

Notice the 0x31 size field: the chunk size is 0x30 (48 bytes) and the lowest bit (1) indicates PREV_INUSE is set. When tcachebins reports 0x30 [ 1]: ..., one freed chunk sits in the 0x30 cache waiting for the next matching allocation.

#Defending and common mistakes

Preventing Use-After-Free and tcache corruption requires combining disciplined lifetime management with compiler and allocator protections:

  • Invalidate pointers on deallocation: Always set pointers to NULL immediately after free(), and ensure no secondary aliases remain in global tables or callbacks.
  • Enable sanitizers during testing: Compile test and fuzz builds with AddressSanitizer (-fsanitize=address) so shadow memory catches temporal reads and writes deterministically in QA.
  • Rely on safer abstractions: Prefer RAII smart pointers in modern C++ or memory-safe languages such as Rust for parsers handling untrusted network input.
  • Keep glibc and compiler hardening current: Modern glibc enables Safe-Linking and tcache key validation by default, raising the cost of metadata tampering when combined with ASLR.

Common mistakes made during heap debugging and remediation:

  • Confusing the user data pointer returned by malloc() with the chunk header address (ptr - 0x10 for prev_size, ptr - 0x08 for size on x86-64).
  • Forgetting that malloc(16) and malloc(24) both map to a 0x20 chunk because an allocated chunk shares the next chunk's prev_size field, leaving 8 bytes of metadata overhead.
  • Assuming free() erases user data from memory; ptmalloc2 only overwrites the first 16 bytes of user space for freelist metadata.
  • Patching only one free() call site while leaving an alias pointer active elsewhere.

#Summary

  • glibc ptmalloc2 manages dynamic memory in 16-byte-aligned chunks whose size field encodes status flags (P, M, A) in its lowest three bits.
  • The per-thread tcache caches up to 7 freed chunks per small size class in LIFO lists, protected in modern glibc by double-free key checks and Safe-Linking pointer mangling.
  • Use-After-Free bugs arise when a dangling pointer outlives free(), enabling stale metadata exposure or type confusion through chunk reuse.
  • Clearing pointers upon free(), enforcing clear object ownership, and testing with AddressSanitizer eliminate UAF flaws before deployment.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge