Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 13 (Oct 6), slide deck
13-malloc-basic. Reading: CS:APP3e §9.9. Lab: L5 (malloclab) is near. Sources: the public Fall 2026 slides and CS:APP. The code is an original teaching allocator (Python) that measures and visualizes the mechanisms. Academic integrity.heap.pyis a concept model, not themalloclabdeliverable (an optimized Cmalloc/free/realloc). These notes contain no lab solution. Code:code/lecture13/. Reading time: ~90 minutes; ~15 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- State what a dynamic allocator does, and the two goals — throughput and memory utilization — it trades off.
- Distinguish internal and external fragmentation and explain where each comes from.
- Describe the implicit free list with boundary tags (header and footer).
- Apply placement policies (first / next / best fit) and explain their trade-off.
- Explain splitting on allocation and the four cases of coalescing on free.
0.2 Prerequisites and scope
- Lectures 11–12: the heap is pages the OS supplies on demand; the allocator carves them.
- Lecture 6: alignment, which forces block rounding.
- In scope: CS:APP §9.9 (dynamic allocation, fragmentation, implicit lists, boundary tags, coalescing). Explicit and segregated lists are Lecture 14.
0.3 Section → code map
| Section | Idea | Demo in code/lecture13/ |
|---|---|---|
| §1 | the allocator’s job; goals | — |
| §2 | fragmentation (internal / external) | 01_fragmentation.py |
| §3 | the implicit free list; boundary tags | 02_coalescing.py |
| §4 | placement, splitting, coalescing | 01_…, 02_… |
1. The allocator’s job
A dynamic memory allocator manages the heap: it hands out variable-sized blocks with malloc and takes them back with free, on request, at run time (when sizes are not known at compile time). The OS gives the process whole pages (Lectures 11–12, via sbrk/mmap); the allocator sub-divides them.
A block is either allocated (handed to the application, which owns its bytes) or free (available). The allocator must satisfy hard constraints: it cannot move or change an allocated block, it cannot assume the order or sizes of requests, and free is given only a pointer, so the allocator must be able to find a block’s size from that pointer alone (§3.1).
Two goals, in tension:
- Throughput: requests served per second —
mallocandfreeshould be fast. - Memory utilization: useful payload as a fraction of the heap — waste little.
Maximizing one hurts the other (best fit packs tightly but searches slowly; a fast allocator fragments more). An allocator is a point on that trade-off curve.
2. Fragmentation
Utilization is never 100% because of fragmentation — memory that is allocated or unusable but not useful payload.
2.1 Internal fragmentation
Internal fragmentation: the block is bigger than the payload. It comes from per-block bookkeeping (the header/footer, §3.1), alignment rounding (payloads to 16 bytes on x86-64, Lecture 6), a minimum block size, and splitting policy. 01_fragmentation.py PART A:
request block size wasted why
1 32 31 16 hdr+ftr + 15 align/min
16 32 16 16 hdr+ftr + 0
100 128 28 16 hdr+ftr + 12 align/min
Every block pays header + footer and rounds up, so small allocations waste a large fraction. Internal fragmentation is predictable and local.
2.2 External fragmentation
External fragmentation: there is enough total free memory, but no single free block is big enough. It builds up as blocks are allocated and freed in a mix, leaving the free space shattered into small pieces. PART B:
filled the 1024-byte heap with 16 blocks of payload 48
freed every other block (8 of them): 512 free bytes total, but the
largest single free block is only 64 bytes.
malloc(200) -> FAILED, even though 512 bytes are free
[....AAAA....AAAA....AAAA....AAAA....AAAA....AAAA....AAAA....AAAA]
Half the heap is free, yet a 200-byte request fails: the free space is a checkerboard of 64-byte gaps. External fragmentation depends on the whole history of requests and is the harder problem — coalescing (§4.3) is the main defense.
3. Keeping track of blocks: the implicit free list
3.1 Headers and boundary tags
free(p) gets only a pointer; the allocator must find the block’s size. The standard trick: store the size (and an allocated bit) in a header word just before the payload. Since blocks are aligned, the low bits of the size are always zero and can hold flags, so one word holds both. Given p, the header is at p - 8.
To also find the previous block (for coalescing, §4.3), each block carries a footer — a copy of the header — at its end. The footer of the previous block sits in the 8 bytes right before the current header, so the allocator reads it in O(1). Header + footer are called boundary tags.
The implicit free list is then just the sequence of all blocks, laid out end to end; “implicit” because the list is defined by the sizes (each header says where the next block begins), not by explicit pointers. Walking it visits every block, free and allocated.
3.2 Finding a free block: placement policy
malloc walks the implicit list looking for a free block that fits. Which one?
- First fit: the first free block big enough. Fast to start, but leaves small splinters near the front that it re-scans every time.
- Next fit: like first fit, but resume where the last search stopped. Avoids re-scanning the front; tends to spread allocations out.
- Best fit: the smallest free block that fits. Wastes the least per allocation, but scans the entire list every time.
01_fragmentation.py PART C measures them on a pressured heap:
policy peak util. failed mallocs steps / malloc
first 0.85 165 11.6
next 0.88 188 8.4
best 0.85 167 18.1
On this workload the policies reach similar utilization, but their search cost differs sharply: best fit scans the most for little packing gain. That is the real lesson — placement is mostly a throughput choice, which is why production allocators make the search cheap (segregated lists, Lecture 14) rather than hunting the best fit.
3.3 Allocating: splitting
When the chosen free block is larger than needed, malloc splits it: carve off a block just big enough for the request and leave the remainder as a smaller free block (if the remainder can hold a minimum block; otherwise give the whole block, accepting the internal fragmentation). 02_coalescing.py PART B:
empty heap: F640
after malloc(32): A64 F576
Splitting avoids handing out a huge block for a small request.
4. Freeing and coalescing
4.1 Freeing
free(p) clears the allocated bit in the header (and footer). But a naive free leaves the heap fragmenting even as memory is returned: two adjacent free blocks remain two blocks, so a later large request may not fit.
4.2 Coalescing
Coalescing merges a freed block with any adjacent free blocks into one larger free block. There are four cases, by whether the previous and next blocks are free. 02_coalescing.py PART A:
Case 1: prev allocated, next allocated -> no merge A96 F96 A96 ...
Case 2: prev allocated, next FREE -> merge next A96 F544
Case 3: prev FREE, next allocated -> merge prev F192 A96 ...
Case 4: prev FREE, next FREE -> merge all three F640
4.3 Why the footer: constant-time coalescing
Merging with the next block is easy — the current header says where it is. Merging with the previous block is the problem: from a pointer alone you cannot walk backward in an implicit list. The footer solves it: the previous block’s footer is in the 8 bytes just before the current header, so the allocator reads the previous block’s size and allocated bit in O(1). That makes cases 3 and 4 constant time instead of a scan from the heap start — the whole point of boundary tags. (Disadvantage: the footer costs 8 bytes on every block, even allocated ones; Lecture 14’s slides show how to drop the footer on allocated blocks.)
Split on malloc, coalesce on free: together they keep free space in as few and as large pieces as possible, holding external fragmentation down.
Summary
- A dynamic allocator carves the heap into variable-sized blocks via
malloc/free, balancing throughput against memory utilization. - Internal fragmentation (block bigger than payload: headers, footers, alignment, rounding) is local and predictable; external fragmentation (free space shattered into unusable pieces) depends on history and is the harder problem.
- The implicit free list lays blocks end to end; each carries a header and, for O(1) backward coalescing, a footer (boundary tags).
free(p)finds the size atp − 8. - Placement (first / next / best fit) is mostly a throughput choice — on a typical workload utilization is similar but search cost differs ~2× (measured), which is why best fit is avoided.
mallocsplits a large free block;freecoalesces with free neighbours (four cases). The footer makes backward coalescing constant time.
Common pitfalls
- Forgetting the header in sizing. A 1-byte
malloccosts a whole block (32 bytes here). Many tiny allocations are mostly overhead. - Equating free bytes with a usable block. External fragmentation means a request can fail with ample free space.
- A naive
freewith no coalescing. The heap degrades into small free blocks; always coalesce. - Losing the ability to find the previous block. Without a footer (or another scheme), backward coalescing is O(heap).
- Splitting into an unusably small remainder. Only split when the remainder can hold a minimum block.
Exercises
-
Block size. With 8-byte headers and footers, 16-byte alignment and a 16-byte minimum payload, how big a block does
malloc(20)need?Answer
Payload rounds up to 32 (align 16), ≥ 16 minimum → 32. Block = 8 (hdr) + 32 + 8 (ftr) = 48 bytes. Internal fragmentation = 48 − 20 = 28. -
Which fits where. Free blocks (in order) of sizes 48, 16, 64, 32. A request needs a 32-byte block. Which block does first fit, next fit (cursor at the 64), and best fit choose?
Answer
First fit: the 48 (first that fits). Next fit from the 64: the 64. Best fit: the 32 (smallest that fits exactly). -
Coalescing case. You free a block whose previous neighbour is allocated and whose next neighbour is free. Which case, and what does the footer have to do with it?
Answer
Case 2 (merge with next). The footer is not needed here — the next block is found from the current header's size. The footer matters for cases 3 and 4 (a free previous block). -
External fragmentation. Why can repeatedly allocating and freeing different sizes cause a large request to fail even though total free memory is large?
Answer
Allocated blocks between free regions prevent those regions from being one contiguous block. The free space is split into pieces each smaller than the request; coalescing only merges *adjacent* free blocks, so non-adjacent free space stays unusable. -
Throughput vs utilization. Why does best fit not clearly beat first fit on utilization in the demo, yet cost much more?
Answer
Best fit scans the whole free list each time (high cost) to shave a few bytes per allocation, but on realistic workloads the packing gain is small and workload-dependent. So it pays a large throughput cost for little utilization gain — hence real allocators use cheaper searches (segregated lists). -
Footer cost. The footer wastes 8 bytes on every block, including allocated ones. When is that cost most painful, and what does Lecture 14 do about it?
Answer
It hurts most with many small blocks (the 8 bytes is a large fraction). Lecture 14 drops the footer on *allocated* blocks by storing the previous block's allocated bit in the current header, keeping footers only on free blocks (which have spare room).
The related lab: L5 (malloclab)
malloclab is to write your own malloc/free/realloc in C, graded on throughput and utilization over trace files. This lecture gives the mechanisms — boundary tags, placement, splitting, coalescing — and the teaching allocator lets you see and measure them, but it is deliberately not a lab solution (Python, and too simple). The exercises rehearse the block arithmetic the lab needs; these notes contain no lab code.
Further reading
- CS:APP3e §9.9; practice problems 9.6–9.10. Figures 9.35–9.40 (the implicit list, boundary tags, coalescing cases) match this lecture’s demos.
- D. Knuth, The Art of Computer Programming Vol. 1 §2.5, the origin of first/best fit and boundary tags.
Preview of Lecture 14: Dynamic memory allocation — advanced
The implicit list’s malloc scans every block, which is too slow. Lecture 14 threads the free blocks into an explicit free list (links stored in the free blocks’ own unused payload), so malloc scans only free blocks, and then into segregated free lists by size class, so it scans only free blocks of about the right size — nearly constant time. It ends with the catalog of C memory bugs (wrong size, off-by-one, use-after-free, double free, leaks) and the tools that catch them.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| dynamic memory allocator | 动态内存分配器 |
| heap | 堆 |
| malloc / free / realloc | 分配 / 释放 / 重新分配 |
| block (allocated / free) | 块(已分配 / 空闲) |
| payload | 有效载荷 |
| throughput | 吞吐量 |
| memory utilization | 内存利用率 |
| fragmentation | 碎片 |
| internal fragmentation | 内部碎片 |
| external fragmentation | 外部碎片 |
| implicit free list | 隐式空闲链表 |
| header / footer (boundary tag) | 头部 / 脚部(边界标记) |
| allocated bit | 分配位 |
| alignment | 对齐 |
| placement policy | 放置策略 |
| first fit / next fit / best fit | 首次适配 / 下次适配 / 最佳适配 |
| splitting (a block) | 分裂(块) |
| coalescing | 合并 |
| bidirectional coalescing | 双向合并 |
| minimum block size | 最小块大小 |