Dynamic Memory Management

the heap break (sbrk and mmap)

/ ES-bee-ar-kay /

When malloc has no free block big enough on its free list, it has to get more memory from somewhere. But malloc itself is just a library function — it does not own any memory; only the operating system does. So malloc must ask the kernel to enlarge the program's heap. The heap break is the boundary marking the current top of the heap, and growing it is how a process gets more raw memory from the OS.

Two system calls do this. The older, simpler one is brk/sbrk: the heap is laid out as a contiguous region that starts after the program's data and grows upward, and the program break is the address marking its current end. Calling sbrk(amount) moves that break up by amount, giving the process that many more bytes of usable heap in one continuous slab. malloc then carves user-sized blocks out of this slab. The second mechanism is mmap, which asks the kernel for a fresh region of memory not tied to the contiguous heap — and modern allocators use mmap for large requests, returning that region directly to the user and unmapping it on free. The key idea either way: malloc gets memory wholesale from the kernel in big chunks (via sbrk or mmap), then retails small pieces of it to your program, keeping the leftovers on its free list.

Why this matters to you as a beginner: it explains why malloc and free are usually fast even though they could involve the kernel. Most allocations are served entirely from memory the allocator already obtained — no system call at all — because crossing into the kernel is comparatively expensive. The allocator only calls sbrk or mmap when it genuinely runs short, and tends to hold onto memory rather than return it eagerly. This is also why a process's memory footprint often grows but rarely shrinks: the allocator keeps the slab to serve future requests, even after you free.

malloc(40) -> free list has a fit -> served instantly, no syscall. malloc(40) -> free list empty -> sbrk(132072) grows the heap once, then this and many future small mallocs are carved from that slab.

The allocator buys memory wholesale from the kernel via sbrk or mmap, then retails small blocks without further syscalls.

This entry covers mmap only as a place malloc gets memory; mmap's role as a paging and file-mapping mechanism is a separate, larger topic in the virtual-memory field.

Also called
program breakbrkwhere memory comes from程式邊界