Part 1 of 7 · 1 min read
Why this page comes first
In this module you will
- Explain why
mallocexists when the kernel already hands out memory. - Name the two system calls that supply memory to the heap,
brkandmmap, and say when each is used. - Trace allocations and frees on a free list, with splitting and coalescing.
- Predict why
freeoften leaves the resident size of a process unchanged. - Write a small arena allocator and say when it is better than
malloc.
Level 6 explained how the kernel gives a process pages, one fault at a time. A C program rarely asks for pages. It asks for 24 bytes for a list node, then 100 bytes for a string, thousands of times. This page shows the layer that turns the kernel's large units into the small ones the program wants. It also pays back several promises of Level 6: the 128 KiB threshold of page 1, and the heap that grows above the program image. The sources are OSTEP chapters 14 and 17, TLPI chapter 7 and OSC chapter 9. The test programs were compiled with gcc -Wall -Wextra and run against glibc 2.39 on Linux, with the container's MALLOC_ environment variables removed so that the default behaviour shows.
About this example About this example
Real: The C programs, commands and outputs on this page were compiled with gcc -Wall -Wextra -pthread and run on a Linux test machine (2 processors, kernel 6.18, glibc 2.39).
Scripted: Numbers marked "made up to show the idea" were chosen for the examples.
Not real: The page simplifies real systems. Actual kernels add more cases, limits and tuning than a short page can show.