#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).
- Metadataprev_size (8B, shared when prev in use) and size + A/M/P flags (8B)
- User Data (when allocated)Application struct fields or string buffer
- 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:
- Double-free detection (
keyfield): Freedtcachechunks store a pointer totcache_perthread_struct(or a randomized cookie in newerglibc) in their second 8-byte slot. Callingfree()twice on the same chunk triggers a bin scan and aborts on match. - Safe-Linking pointer mangling: Since
glibc2.32,tcacheandfastbinforward 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.
- Program calls free(ptr)Check chunk size fits tcache (0x20-0x410)
- Validate key fieldAbort if chunk already present in bin
- Mangle next pointerApply Safe-Linking XOR with (addr >> 12)
- 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'stcachemetadata (such as the mangledfdpointer orkey), 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
tcachesize 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:
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.
$ 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 -> 0x0Notice 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
NULLimmediately afterfree(), 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
glibcenables Safe-Linking andtcachekey 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 - 0x10forprev_size,ptr - 0x08forsizeon x86-64). - Forgetting that
malloc(16)andmalloc(24)both map to a0x20chunk because an allocated chunk shares the next chunk'sprev_sizefield, leaving 8 bytes of metadata overhead. - Assuming
free()erases user data from memory;ptmalloc2only 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 ptmalloc2manages dynamic memory in 16-byte-aligned chunks whosesizefield encodes status flags (P,M,A) in its lowest three bits.- The per-thread
tcachecaches up to 7 freed chunks per small size class in LIFO lists, protected in modernglibcby double-freekeychecks 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.