A01 — The Internals of malloc: How brk and mmap Work Together
Key Insight: Every block of memory you allocate with malloc is backed by the system making allocation decisions on your behalf.
malloc is Not a System Call
malloc is a glibc (ptmalloc) library function, not a system call.
Two paths for malloc:
1. brk/sbrk (system call) — small objects (<= 128KB)
2. mmap/munmap (system call) — large objects (> 128KB)
Performance:
- brk: ~10ns (user-space operation)
- mmap: ~500ns (system call + TLB miss)How brk Works
brk system call adjusts the program break (heap top).
- brk expands heap upward, shrinks downward
- Only the top chunk can shrink
- Freed chunks are not returned to kernel immediatelyHow mmap Works
mmap creates anonymous mappings for large allocations.
- Allocates virtual memory, physical pages on demand
- munmap frees entire block at once
- No fragmentation, clean deallocationmalloc's Complete Strategy
size <= 128KB → brk path (fast, user-space)
size > 128KB → mmap path (system calls, clean)
Threshold adjustable via mallopt(M_MMAP_THRESHOLD)
Comments