TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › The Heap and glibc malloc, Conceptually

The Heap and glibc malloc, Conceptually

The stack holds data whose lifetime matches a function call. Everything else (a request body, a parsed image, a session object that outlives the function that created it) lives on the heap, managed by the C library's allocator through malloc, realloc and free. The allocator is ordinary C code that keeps its bookkeeping inside the heap, right next to your data. A heap overflow, a double free or a use-after-free therefore corrupts not only other objects but the allocator's own records, and the allocator's later decisions (which block to hand out next, where to write a list pointer) are driven by those records. This lesson explains the design of glibc's allocator (ptmalloc) at the level a reviewer needs: what a chunk is, where its header lives, and what the allocator checks. How C programs use malloc is covered in C Memory Management.

Definitions

  • Chunk: the allocator's unit. A chunk is a size header followed by the user's bytes. malloc returns a pointer just after the header.
  • Size field: 8 bytes before the user pointer on 64-bit Linux, holding the chunk size (a multiple of 16) with three flag bits in the low bits; bit 0, PREV_INUSE, says the chunk before this one is in use.
  • Usable size: how many bytes the program may really use, malloc_usable_size(p). Requests are rounded up so that chunks are 16-byte aligned; the minimum chunk is 32 bytes.
  • Free lists ("bins"): freed chunks are kept in lists by size, so they can be handed out again. glibc has, from fastest to most general: per-thread tcache bins (since glibc 2.26; by default 7 chunks per size, for requests up to 1032 bytes on 64-bit), fastbins, an unsorted bin, small and large bins.
  • Top chunk: the free space at the end of the heap from which new chunks are cut. Requests of 128 KiB and more (the default M_MMAP_THRESHOLD) are served by a separate mmap instead.
  • Arena: one heap with its own lists; threads may use different arenas to avoid lock contention.
size A0x21 A: 24 usable bytesp = malloc(24) size B0x21 B: 24 usable bytesq = malloc(24) p q = p + 32 writing 32 bytes from p reaches B's size field size 0x21 = chunk of 32 bytes (0x20) + PREV_INUSE flag (1)

Looking at real chunks

The session asks glibc for blocks of five sizes, reads each block's size field (the 8 bytes before the pointer), and measures the distance between consecutive blocks. Distances between blocks of a fresh heap are the same on every run even though ASLR moves the heap. Then it frees one block and allocates the same size again. It runs in your sandbox:

bash · try it yourself
cat > chunks.c <<'SRC'
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t req[] = {1, 24, 25, 40, 100};
    char *p[5];
    for (int i = 0; i < 5; i++) p[i] = malloc(req[i]);
    for (int i = 0; i < 5; i++) {
        size_t hdr = ((size_t *)p[i])[-1];            /* the chunk's size field */
        printf("malloc(%3zu): usable %3zu, chunk size %3zu, flags %zu",
               req[i], malloc_usable_size(p[i]), hdr & ~(size_t)7, hdr & 7);
        if (i) printf(", %3td bytes after the previous block", p[i] - p[i - 1]);
        printf("\n");
    }
    free(p[1]);
    char *again = malloc(24);
    printf("free then malloc(24) again: same block? %s\n", again == p[1] ? "yes (tcache, last in first out)" : "no");
    for (int i = 0; i < 5; i++) if (i != 1) free(p[i]);
    free(again);
    return 0;
}
SRC
gcc -g -O0 chunks.c -o chunks && ./chunks
malloc(  1): usable  24, chunk size  32, flags 1
malloc( 24): usable  24, chunk size  32, flags 1,  32 bytes after the previous block
malloc( 25): usable  40, chunk size  48, flags 1,  32 bytes after the previous block
malloc( 40): usable  40, chunk size  48, flags 1,  48 bytes after the previous block
malloc(100): usable 104, chunk size 112, flags 1,  48 bytes after the previous block
free then malloc(24) again: same block? yes (tcache, last in first out)

Three facts to take away:

  1. Rounding. A 1-byte request gets a 32-byte chunk with 24 usable bytes; 25 bytes need the next size, 48. The program may only rely on what it asked for: writing byte 2 of a 1-byte block is a bug even though glibc wouldn't notice. ASan would, because it poisons everything past the requested size.
  2. Adjacency. Blocks are cut one after another from the top chunk, so the block after a 24-byte block starts 32 bytes later, and its size field sits in the 8 bytes right after the first block's usable area. The flag value 1 (PREV_INUSE) says the previous chunk is in use.
  3. Reuse. A freed chunk goes to the tcache, and the next request of the same size gets the same address back, last in, first out. This is what makes use-after-free dangerous: the dangling pointer soon points into a different, live object.

What corruption does to the allocator

When a block is freed, glibc stores list pointers in the block's own user area (the tcache's "next" pointer is the first 8 bytes), and when chunks are merged it trusts the size fields. An overflow from one block into the next block's size field therefore corrupts the allocator's view of the heap. Modern glibc checks its records at every free and malloc and aborts when they are inconsistent:

bash · try it yourself
cat > hdr.c <<'SRC'
#include <stdlib.h>
#include <string.h>
int main(void) {
    char *a = malloc(24), *b = malloc(24);
    memset(a, 'A', 24 + 8);        /* BUG: 8 bytes too many, onto b's size field */
    free(b);
    free(a);
    return 0;
}
SRC
gcc -g -O0 hdr.c -o hdr 2>/dev/null
./hdr 2>&1 | cat; echo "exit code: ${PIPESTATUS[0]}"
double free or corruption (out)
exit code: 134

free(b) read a size field of 0x4141414141414141; by that size the next chunk would lie far beyond the end of the heap, so glibc aborted with double free or corruption (out) (SIGABRT, exit code 134). The message names a check, not the bug: the real bug was the memset one line earlier, and only ASan points there. (GCC also warned at compile time with -Wstringop-overflow, hidden here with 2>/dev/null.)

The allocator's own defences

Allocator exploitation has a long history, and each technique was answered with a check: glibc verifies that a chunk's size is plausible and aligned, that list links are consistent before unlinking, that a chunk being freed isn't already in its tcache bin (since glibc 2.29 every chunk in the tcache carries a key; a free that finds the key searches the bin and aborts with free(): double free detected in tcache 2) or at the head of its fastbin (double free or corruption (fasttop)), and since glibc 2.32 it mangles the tcache and fastbin pointers by XORing each with the address it is stored at, shifted right by 12 bits ("safe-linking"): with ASLR those bits are random, so an overwritten list pointer is unlikely to decode to a useful address, and glibc also rejects decoded pointers that aren't 16-byte aligned. Hardened allocators go further and keep metadata away from user data entirely (Memory Tagging and Hardened Allocators). None of this is a substitute for fixing the overflow: the checks catch some corruptions, at some time, after the fact.

How heap bugs are detected

ASan replaces glibc's allocator with its own, which puts red zones around every block, records the allocation and free stack of each, and holds freed blocks in quarantine. That is why ASan's reports can say "0 bytes after 24-byte region, allocated here, freed there". Without ASan, glibc's abort messages (malloc(): corrupted top size, free(): invalid next size (fast), double free or corruption) in a log are strong evidence of heap corruption; treat them as security bugs. Valgrind's Memcheck finds the same classes without recompiling, much more slowly.

Pitfalls

  • Relying on usable size. Code that writes into the rounding slack works with glibc and fails with ASan or another allocator. It is still an overflow.
  • Reading the size field yourself (as the demo does) is a teaching trick, not an API. Never do it in real code; use malloc_usable_size only for diagnostics.
  • realloc moves blocks. Every pointer into the old block is dangling after a realloc that moved it.

Practice

1. What chunk size and usable size does glibc give for malloc(48)?

48 + 8 for the size field = 56, rounded up to a multiple of 16 = 64-byte chunk; usable size 64 − 8 = 56.

2. Why does a use-after-free often read data of a different object?

Because of LIFO reuse: after free(p), the next allocation of a similar size gets the same address, so the dangling p now aliases the new object.

3. The overflow in hdr.c was 8 bytes. Which byte of a was the first one out of bounds, and which part of b did it hit?

a[24], the first byte past the 24 requested (and usable) bytes. Bytes a[24]..a[31] are b's size field.

Test yourself

Where does glibc keep a chunk's size?

  1. In a separate table
  2. In the 8 bytes just before the pointer returned by malloc
  3. At the end of the block
  4. In the stack

After free(p) and q = malloc(same size), what did the session show?

  1. q is always NULL
  2. q == p: the tcache hands the freed block back, last in first out
  3. q is on the stack
  4. q is 32 bytes after p

glibc aborted with 'double free or corruption (out)' in hdr.c. Where was the bug?

  1. In free(b)
  2. In the memset one line earlier, which overwrote b's size field
  3. In glibc
  4. In malloc

What does glibc's safe-linking (2.32+) protect?

  1. The stack canary
  2. The tcache and fastbin list pointers stored in freed chunks, by XORing them with ASLR-randomised bits of their own storage address
  3. The GOT
  4. Thread stacks