Skip to content
Visual explainer 5h to learn 5 steps

malloc internals & a simple allocator

Explain how malloc obtains and recycles memory and write a basic allocator.

By Invicly Tech, , in Linux System Programming. About 14 minutes to read.

Topic 31 of 42

In short

malloc is user-space library code that carves memory obtained from the kernel into small blocks. glibc grows the heap with brk for small requests and calls mmap directly for large ones, 128 KiB and up by default. Freed blocks go into bins and caches for reuse, which is why an overflow or double free corrupts state far from the bug.

Explained simply

malloc is not a system call. It is ordinary C code inside the C library. Asking the kernel for memory is slow and works in whole pages, so malloc asks for big pieces now and then and cuts them into the small blocks your program wants.

Each block has a small hidden label in front of it that stores its size. That is how free knows how much to give back without you telling it. It is also why writing past the end of a block is so dangerous: you overwrite the next block's label, and the program crashes later, somewhere else.

When you free a block, malloc usually keeps it for reuse instead of returning it to the kernel. Freed blocks are sorted into lists by size, so the next malloc of a similar size is fast.

Building your own small allocator is the best way to understand all this. With LD_PRELOAD you can even make real programs like ls use your allocator without recompiling them.

Press Play on a diagram to walk through it one step at a time.

MapWhere a glibc malloc call gets memory
malloc(n)
  • Small request
    • Per-thread cache (tcache)
    • Bins of freed chunks
    • Split from the top of the heap
  • Heap grows
    • brk moves the program break up
  • Large request (about 128 KiB or more)
    • Direct mmap
    • Returned to the kernel on free
  • Every chunk
    • Header with size and flags
    • User data right after the header
FlowWhat happens in free(p) in glibc, simplified
  1. 1
    Read the header

    Size and flags just before p

  2. 2
    mmapped chunk?

    Yes: munmap it right away

  3. 3
    Room in tcache?

    Yes: push on this thread's list, no lock

  4. 4
    Lock the arena

    Small chunks may go to a fast bin

  5. 5
    Merge free neighbours

    Then place in the unsorted bin

  6. 6
    Big free space at top?

    Above trim threshold: shrink with brk

In depth

Where the memory comes from: brk and mmap

glibc malloc has two sources. For normal requests it uses the main heap, a region right after the program's data whose end is called the program break. When the heap runs out, malloc calls brk (through sbrk) to move the break up, typically by 132 KiB or more at a time. When enough free space gathers at the very top, free can move the break back down, controlled by M_TRIM_THRESHOLD (128 KiB by default).

Requests at or above M_MMAP_THRESHOLD (128 KiB by default) skip the heap and get their own anonymous mmap. free then calls munmap, so that memory really returns to the kernel at once. The threshold is dynamic: when you free an mmapped block, glibc raises the threshold to that size (up to 32 MiB on 64-bit), betting that you will allocate it again soon. Setting the threshold yourself with mallopt turns this off.

You can watch it all with strace -e trace=brk,mmap,munmap ./prog.

  • Small: carved from the heap, grown with brk
  • Large (128 KiB or more): direct mmap, munmap on free
  • malloc_trim(0) asks glibc to return free heap memory

Chunks, headers and bins in glibc

Every allocation is a chunk. On 64-bit glibc the chunk starts with an 8-byte size field, and the pointer you get back points just after it. Sizes are multiples of 16, so the low 3 bits of the size field are free and used as flags: PREV_INUSE (the chunk before is in use), IS_MMAPPED and NON_MAIN_ARENA. The smallest chunk is 32 bytes, so even malloc(1) uses 32. malloc_usable_size(p) tells you how much room you actually got.

When a chunk is freed, its user area is reused to store list pointers to other free chunks. Free chunks are kept in bins. The fastest path is the tcache, a per-thread cache (since glibc 2.26) with 64 size classes up to 1032 bytes, each holding up to 7 chunks, and no locking at all. Behind it are fast bins, an unsorted bin, small bins of one size each and large bins of size ranges. Neighbouring free chunks are merged (coalesced) to fight fragmentation.

LayersOne glibc chunk on 64-bit
  1. 1
    prev_size (8 bytes)

    Size of the previous chunk, only valid if it is free

  2. 2
    size | flags (8 bytes)

    Chunk size; low bits: PREV_INUSE, IS_MMAPPED, NON_MAIN_ARENA

  3. 3
    User data

    malloc returns a pointer here, 16-byte aligned

  4. 4
    When free: list pointers

    fd and bk link the chunk into a bin

  5. 5
    Next chunk's header

    Overflowing your data corrupts this

Fragmentation and arenas

Fragmentation is memory you cannot use. Internal fragmentation is waste inside a block, like the 31 spare bytes of malloc(1). External fragmentation is free space split into holes too small for the next request. A long-running server that allocates many small objects and frees most of them can end up with a heap full of holes: the program uses 200 MiB, but RSS stays at 2 GiB, because one live object at the top of the heap stops brk from shrinking.

Threads add another problem: contention. glibc gives the program several arenas, each an independent heap with its own lock. The main arena uses brk; extra ones are mmapped heaps of 64 MiB each. A thread usually keeps using one arena, and the limit is 8 arenas per CPU core on 64-bit. More arenas mean less lock contention but more memory held in partly used heaps. Setting MALLOC_ARENA_MAX=2 is a common fix for services whose memory grows with thread count. Alternative allocators such as jemalloc, tcmalloc and mimalloc make different trade-offs and often fragment less.

  • MALLOC_ARENA_MAX=2 ./server limits the number of arenas
  • malloc_stats() prints per-arena usage to stderr
  • LD_PRELOAD=libjemalloc.so.2 tries jemalloc without rebuilding

Making the toy allocator real

The explainer's first-fit allocator works, but it has gaps a real one must fill. Splitting: when a free block is much bigger than the request, cut it in two and keep the rest on the free list, or one malloc(16) can swallow a 1 MiB block. Coalescing: when a block is freed next to another free block, merge them, which needs a way to find neighbours (a size field at both ends, called a boundary tag). Alignment: every pointer must be aligned to 16 bytes on x86-64, so round sizes up and keep the header size a multiple of 16.

Thread safety: wrap every operation in one mutex, or give each thread its own cache. Overflow: calloc(n, size) must check that n * size does not overflow before allocating. And a full replacement must provide malloc, free, calloc and realloc, and ideally also posix_memalign, aligned_alloc and malloc_usable_size, because a program that gets memory from one allocator and frees it with another will crash.

  • Split big free blocks; merge neighbours on free
  • Round every size up to a multiple of 16
  • calloc: if (n && size > SIZE_MAX / n) return NULL;

Testing with LD_PRELOAD

The dynamic loader reads the LD_PRELOAD variable and loads those shared libraries before any others. Symbols they define win, so a library that defines malloc and free replaces the ones in libc for the whole program, including calls made inside other libraries. Build it with gcc -shared -fPIC -O2 -o libmy.so my.c -pthread and run LD_PRELOAD=./libmy.so ls.

Three traps catch everyone. Do not call printf inside malloc: printf may call malloc, which recurses until the stack overflows. Use write(2, ...) with a fixed buffer for debug output. Second, LD_PRELOAD does nothing for statically linked programs, and it is mostly ignored for setuid programs for security. Third, the first program you test with may call functions you did not provide, such as realloc, and mix allocators; start with small tools like ls and cat, then try bigger ones.

To debug your heap code, link it into a small test program first and step through it with gdb. Do not combine it with AddressSanitizer, which brings its own malloc.

FlowHow LD_PRELOAD swaps malloc
  1. Step 1
    Program starts

    The dynamic loader ld.so runs first

  2. Step 2
    Load LD_PRELOAD libs

    libmy.so is searched before libc

  3. Step 3
    Resolve malloc

    First definition found wins: yours

  4. Step 4
    Every malloc call

    From the program and all its libraries

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Explain brk, sbrk and mmap for allocation~1h
  2. 2
    Describe chunks, headers and free lists~1h
  3. 3
    Explain fragmentation and arenas~1h
  4. 4
    Write a first-fit allocator~1h
  5. 5
    Test it with LD_PRELOAD~1h

Key points

  • malloc and free are library code; only brk and mmap are system calls.
  • Each block has a hidden header storing its size, so free needs no length.
  • Fragmentation can leave memory unusable even when plenty is free in total.
  • glibc uses several arenas to reduce lock contention between threads.
  • LD_PRELOAD lets you swap in another allocator without recompiling.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <stddef.h>
#include <unistd.h>

typedef struct hdr { size_t size; struct hdr *next; } hdr;
static hdr *free_list;

void *my_malloc(size_t n) {
  n = (n + 15) & ~(size_t)15;                      // 16-byte alignment
  for (hdr **pp = &free_list; *pp; pp = &(*pp)->next)
    if ((*pp)->size >= n) { hdr *h = *pp; *pp = h->next; return h + 1; }
  hdr *h = sbrk(sizeof(hdr) + n);                   // grow the heap
  if (h == (void *)-1) return NULL;
  h->size = n; return h + 1;
}
void my_free(void *p) { if (p) { hdr *h = (hdr *)p - 1; h->next = free_list; free_list = h; } }

A first-fit free-list allocator (single-threaded, never splits or merges blocks).

See brk and mmap with strace

We allocate one small and one large block and watch the system calls. Step 1: the small malloc(1000) causes one brk call that grows the heap by about 132 KiB; later small mallocs need no system call at all. Step 2: malloc(1 MiB) is above the 128 KiB threshold, so it becomes its own mmap of a little more than 1 MiB (the extra page holds the chunk header). Step 3: freeing the large block calls munmap at once, while freeing the small one makes no system call.

bash
cat > m.c <<'EOF'
#include <stdlib.h>
int main(void) {
  char *s = malloc(1000), *l = malloc(1 << 20);
  free(l); free(s); return 0; }
EOF
gcc -O0 m.c -o m
strace -e trace=brk,mmap,munmap ./m
# ... first, the loader maps libc and other libraries ...
# brk(0x55d5c2a70000)             = 0x55d5c2a70000   small block: heap grows
# mmap(NULL, 1052672, PROT_READ|PROT_WRITE, ...) = 0x7f2a1c000000   large block
# munmap(0x7f2a1c000000, 1052672) = 0             freed straight back

Turn the toy allocator into a preloadable library

We wrap the explainer's my_malloc and my_free so real programs can use them. Step 1: one global mutex makes every call thread-safe. Step 2: calloc checks for multiplication overflow, then zeroes the block, because reused blocks contain old data. Step 3: realloc handles NULL, keeps the block if it is already big enough (the header stores the rounded size), and otherwise copies. Step 4: build with gcc -shared -fPIC -pthread and run LD_PRELOAD=./libmy.so ls. Programs that call posix_memalign or aligned_alloc would still need those too.

c
#include <pthread.h>
#include <stdint.h>
#include <string.h>
static pthread_mutex_t lk = PTHREAD_MUTEX_INITIALIZER;   /* plus hdr, my_malloc, my_free */
void *malloc(size_t n) { pthread_mutex_lock(&lk); void *p = my_malloc(n); pthread_mutex_unlock(&lk); return p; }
void free(void *p)     { pthread_mutex_lock(&lk); my_free(p); pthread_mutex_unlock(&lk); }
void *calloc(size_t c, size_t n) {
  if (n && c > SIZE_MAX / n) return NULL;                /* c * n would overflow */
  void *p = malloc(c * n); if (p) memset(p, 0, c * n); return p;
}
void *realloc(void *old, size_t n) {
  if (!old) return malloc(n);
  size_t have = ((hdr *)old - 1)->size; if (n <= have) return old;
  void *p = malloc(n); if (p) { memcpy(p, old, have); free(old); } return p;
}

Quick reference

  • glibc: under 128 KiB from the brk heap; 128 KiB and up via mmap (threshold adapts)
  • 64-bit glibc: 16-byte alignment, minimum chunk 32 bytes, 8-byte size header
  • malloc_usable_size(p) shows the real usable size of a block
  • strace -e trace=brk,mmap,munmap ./prog shows where memory comes from
  • MALLOC_ARENA_MAX=2 reduces memory growth in heavily threaded services
  • malloc_trim(0) returns free heap memory to the kernel where possible
  • LD_PRELOAD=./libmy.so prog replaces malloc for dynamically linked programs
  • Never call printf inside your malloc: it can recurse; use write(2, ...)

Common mistakes

  • Writing past a block's end and corrupting the next chunk's header.
  • Mixing allocators, such as passing mmap memory to free.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which of these is a system call?

Question 2

2On 64-bit glibc with default settings, how is malloc(4 MiB) usually served?

Question 3

3A server uses 200 MiB of live data but its RSS stays at 2 GiB after a traffic spike. What is the most likely cause?

Question 4

4Why must calloc check n * size for overflow?

Question 5

5Your preloaded malloc prints a debug line with printf, and every program now crashes. Why?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print malloc_usable_size for malloc(1), malloc(24), malloc(25) and malloc(100). Explain the numbers from the 16-byte rounding and the 8-byte header.

  2. Exercise 2medium

    Add splitting to the explainer's first-fit allocator: when a free block has at least sizeof(hdr) + 32 bytes more than needed, cut off the rest as a new free block.

  3. Exercise 3hard

    Write a preloadable library that does not replace malloc but counts calls: wrap malloc and free, forward to the real ones with dlsym(RTLD_NEXT, ...), and print totals at exit with write.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does free return memory to the operating system?
Sometimes. Large mmapped blocks are returned at once. Small blocks usually stay inside the process for reuse, and the heap only shrinks when free space at its top passes the trim threshold.
Why does my program crash in free and not where the bug is?
An earlier overflow or double free corrupted the hidden chunk headers, and glibc only notices when it later walks them. Run the program with AddressSanitizer or valgrind to find the real bad write.
Is jemalloc or tcmalloc better than glibc malloc?
For many multithreaded servers they use less memory and scale better, which is why projects like Redis and FreeBSD use jemalloc. Measure with your own workload; LD_PRELOAD makes trying them easy.
Why is malloc thread-safe but sometimes slow with many threads?
Arenas have locks. The per-thread tcache avoids locks for small, recently freed sizes, but other requests take an arena lock, so heavy allocation in many threads can contend.

Go deeper

ShareXLinkedInWhatsApp