The Runtime Theory

Memory Allocation Path

The allocation path from malloc to physical memory: size classes, thread-local free lists, brk heap growth, mmap, and demand paging.

The Runtime Theory Team07 stages

trace / request.md

ALLOCATIONREQUESTSIZE-CLASS LOOKUPFAST PATH: REUSEHEAP GROWTHVIA BRKMMAP FORLARGE OBJECTSFIRST TOUCHFAULTSVIRTUAL ADDRESSRETURNED

readymalloc, new, or the runtime's own allocator asks for N bytes. The request is rounded up to a fixed size class — 16, 32, 48 bytes and so on — before anything else.

Allocation is a path with a fast lane and slow lanes. This diagram traces one malloc-sized request: size-class lookup, a thread-local free-list hit — the fast path, no locks, no syscalls — and the misses that fall through to brk/sbrk to extend the heap, or mmap for very large objects. The ordering matters because each fallback is progressively more expensive: a tcache pop is a few instructions, brk is a syscall, and first touching a brand-new page costs a page fault that materializes physical memory. The diagram shows the virtual address the program receives and the physical pages appearing lazily on write. The end state: the program holds a pointer, the heap is slightly larger, and physical backing exists only where the program has actually written.