Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 14 (Oct 8), slide deck
14-malloc-advanced. Reading: CS:APP3e §9.9–9.11. Lab: L5 (malloclab) in progress. Sources: the public Fall 2026 slides and CS:APP. The code extends Lecture 13’s teaching allocator (Python) and runs real buggy C programs under AddressSanitizer. Academic integrity.heap.py/freelists.pyare concept models, not themalloclabdeliverable. No lab solution here. Code:code/lecture14/. Reading time: ~85 minutes; ~20 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain the explicit free list — free blocks threaded into their own doubly-linked list, with links stored in the blocks’ unused payload — and the LIFO free policy.
- Explain the segregated free list (seglist) — one free list per size class — and why it gives near-constant-time allocation.
- Compare the search cost of implicit, explicit and segregated allocators.
- Recognize the common C memory bugs (wrong size, off-by-one, uninitialized read, use-after-free, double free, leak) and choose the tool that catches each.
0.2 Prerequisites and scope
- Lecture 13: implicit free list, boundary tags, placement, splitting, coalescing.
- Lecture 8: debugging tools (ASan, UBSan, valgrind).
- In scope: CS:APP §9.9.13–9.9.14 (explicit and segregated lists) and §9.11 (memory-related bugs).
0.3 Section → code map
| Section | Idea | Demo in code/lecture14/ |
|---|---|---|
| §1 | explicit free lists; LIFO | 01_free_lists.py |
| §2 | segregated free lists | 01_free_lists.py |
| §3 | the comparison | 01_free_lists.py |
| §4 | C memory bugs and tools | 02_memory_bugs.py |
1. Explicit free lists
The implicit list’s malloc scans every block — allocated ones too — so its cost grows with the whole heap. But malloc only cares about free blocks. An explicit free list threads just the free blocks into a doubly-linked list, so a search visits only free blocks.
The elegant part: a free block’s payload area is unused, so the prev/next list pointers live inside the free block itself — the explicit list costs no extra memory beyond what a free block already has. (An allocated block needs no links; it reclaims that space for payload.)
On free, where does the newly free block go in the list? The simplest policy is LIFO: push it on the front. Freeing is then O(1) (coalesce, then insert at head), at some cost to locality and fragmentation versus address-ordered insertion. The slides walk the four LIFO cases (whether each neighbour was free), which mirror Lecture 13’s coalescing cases plus the list splice.
The payoff: malloc is now O(number of free blocks), not O(all blocks).
2. Segregated free lists
A single free list still gets long when there are many free blocks. A segregated free list keeps several free lists, one per size class (e.g. {16}, {24–32}, {33–64}, {65–128}, …, {big}). malloc(n):
- picks the class for
n, - searches that class’s (short) list for a fit; if none, tries larger classes,
- splits as usual, and puts any remainder on the class for its size.
Because each list holds only blocks of roughly one size, the search is short regardless of how many free blocks exist overall — effectively constant time, while still getting a good fit (the class already matches the size). This is how real allocators (glibc’s bins, tcmalloc, jemalloc) are built. It also improves utilization versus plain first fit, because same-size blocks cluster.
3. The comparison
01_free_lists.py runs the same seeded workload on each organization and counts blocks examined per malloc, at equal utilization:
allocator steps / malloc peak utilization
implicit (first fit) 49.4 0.83
implicit (best fit) 71.7 0.84
explicit free list 5.4 0.82
segregated (8 classes) 1.3 0.83
Reading it:
- Implicit scans allocated blocks too — most expensive (best fit scans the whole list every time, 71.7).
- Explicit scans only free blocks — ~9× fewer steps than implicit first fit.
- Segregated scans only free blocks of about the right size — ~1.3 steps, about 39× fewer than implicit, at the same utilization.
Same fragmentation, hugely different throughput. This is why production allocators are segregated-fit: the lesson from Lecture 13 (make the search cheap, don’t hunt the best fit) taken to its conclusion. (The model counts search steps; a real explicit list keeps its links inside the free blocks, so this speed comes at no memory cost.)
4. Memory-related perils and pitfalls
The slides close with the catalog of C heap bugs (CS:APP §9.11). They share a nasty trait: the symptom often appears far from the cause and long after it — Lecture 1’s “action at a distance”. 02_memory_bugs.py runs each and shows the tool that catches it.
4.1 The bugs
- Wrong allocation size —
malloc(n * sizeof(p))where you meantsizeof(*p). If the element is bigger than a pointer, the block is too small and later writes overflow it. (malloc(8 * sizeof(int))for 8long*allocates 32 bytes for 64 needed.) - Off-by-one —
for (i = 0; i <= n; i++) a[i] = …writes one element past the end. - Reading uninitialized memory — heap from
mallocis not zeroed (usecallocif you need zeros). - Use-after-free — reading or writing a block after
free; the allocator may have reused it. - Double free —
freeing the same block twice; corrupts the allocator’s own structures. - Memory leak — losing the last pointer to a block without
freeing it; the memory is unreachable but never reclaimed. - Plus dereferencing bad pointers (null, wild) and off-by-one on the terminator / pointer-arithmetic scaling mistakes.
4.2 Catching them
wrong-size -> ASan: heap-buffer-overflow (bugs14.c:28)
off-by-one -> ASan: heap-buffer-overflow (bugs14.c:36)
use-free -> ASan: heap-use-after-free (bugs14.c:46)
double-free -> ASan: double-free (bugs14.c:52)
leak -> counting allocator: 3 live blocks, 300 bytes still allocated at exit
AddressSanitizer turns the four access/lifetime bugs into immediate, located errors. Built plain, the same programs variously ran to completion with a corrupted result, or were killed by the system allocator’s guards with no explanation — the silent, baffling failures that make heap bugs expensive.
A leak is different: it is not an illegal access, so ASan’s access checks miss it. You need a leak checker — LeakSanitizer or valgrind on Linux, the leaks tool on macOS — or you track live bytes yourself, as the demo’s counting allocator does. (LeakSanitizer is unavailable on arm64 macOS, which is why the demo uses the counting wrapper.)
The habit: build and test allocator-heavy code under a sanitizer from the start (-fsanitize=address,undefined), and run a leak check before you trust it. malloclab especially rewards this.
Summary
- An explicit free list threads only the free blocks together, with
prev/nextstored in their unused payload (no extra memory), somallocscans only free blocks; LIFO insertion makesfreeO(1). - A segregated free list keeps one list per size class, so
mallocscans only free blocks of about the right size — near constant time — and fits well. Production allocators are segregated-fit. - Measured at equal utilization, search cost falls from ~49 (implicit) to ~5 (explicit) to ~1.3 (segregated) steps per
malloc— the throughput win with no utilization loss. - The C heap bugs — wrong size, off-by-one, uninitialized read, use-after-free, double free, leak — are undefined behavior that fails silently or far away. ASan catches the access/lifetime bugs with a line; a leak checker (or tracking) is needed for leaks. Test under these tools from the start.
Common pitfalls
sizeofthe pointer, not the pointee.malloc(n * sizeof(p))under-allocates when the element is larger than a pointer. Writemalloc(n * sizeof(*p)).<=in a loop bound.i <= ntouchesa[n], one past the end.- Assuming
malloczeroes. It does not; usecalloc, or initialize. - Using or freeing a block twice. Null the pointer after
freeto make a reuse fault loudly. - Losing a pointer. Overwriting the only pointer to a block (e.g.
p = malloc(...)in a loop without freeing) leaks it. - Trusting a plain run. “It didn’t crash” is not “no bug”; run ASan and a leak checker.
Exercises
-
Why no extra memory. How does an explicit free list store its links without growing the block?
Answer
The links go in the free block's payload area, which is unused while the block is free. An allocated block needs no links, so it uses that space for payload. The list is free to maintain. -
Seglist search. With size classes {16}, {32}, {64}, {128+}, which list(s) does
malloc(40)search, and why is it fast even with thousands of free blocks?Answer
40 rounds to the {64} class; search that list, then larger classes if empty. Each list holds only blocks of one class, so the search is short no matter how many free blocks of *other* sizes exist — nearly constant time. -
LIFO free. Why is freeing O(1) with a LIFO explicit list?
Answer
Coalesce with neighbours (O(1) via boundary tags), then splice the block onto the front of the free list (O(1) pointer updates). No search for a position. -
Diagnose.
long *v = malloc(n * sizeof(int)); for (i=0;i<n;i++) v[i]=i;— what is wrong, and which tool names it?Answer
`sizeof(int)` (4) but `v` holds `long` (8): the block is half the needed size, so the loop overflows it. AddressSanitizer reports a heap-buffer-overflow at the write, with the line. -
Right tool. Match: (a) reading
a[n]; (b)free(p); free(p);; (c) forgetting to free in a loop; (d)*pafterfree(p).Answer
(a), (b), (d): AddressSanitizer (heap-buffer-overflow; double-free; heap-use-after-free). (c): a leak checker — LSan/valgrind/`leaks` — not ASan's access checks. -
Throughput math. The demo shows implicit first fit at 49 steps/malloc and segregated at 1.3. For 10⁶ mallocs, roughly how many block examinations does each do?
Answer
Implicit ≈ 49 × 10⁶ ≈ 4.9 × 10⁷ examinations; segregated ≈ 1.3 × 10⁶. About 38× fewer — the difference between a sluggish allocator and a fast one, at the same memory utilization.
The related lab: L5 (malloclab)
This lecture’s explicit and segregated lists are exactly the techniques a competitive malloclab allocator uses to get throughput, and §4’s bug catalog is the set of mistakes that will plague your implementation — build it under -fsanitize=address and a leak checker from the first line. The teaching allocator here measures the ideas but is not a lab solution (Python, and it omits the real link management). These notes contain no lab code.
Further reading
- CS:APP3e §9.9.13–9.9.14 (explicit/segregated lists) and §9.11 (memory bugs); practice problems 9.11–9.13.
- The glibc
mallocinternals (bins and arenas) and the jemalloc/tcmalloc design notes, for how segregated fit is done in production. - The AddressSanitizer, LeakSanitizer and valgrind documentation (Lecture 8).
Preview of Lecture 15: Code optimization
You have made memory fast (Lectures 9–14); Lecture 15 is about making the computation fast. It covers what a compiler can and cannot optimize (and the “optimization blockers” — memory aliasing, function calls — that stop it), the processor’s instruction-level parallelism, and how to expose it in your code with loop unrolling and multiple accumulators, up to the point where the memory system (this unit) becomes the bottleneck again.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| explicit free list | 显式空闲链表 |
| doubly-linked list | 双向链表 |
| LIFO (last-in first-out) policy | 后进先出策略 |
| address-ordered policy | 地址有序策略 |
| segregated free list (seglist) | 分离空闲链表 |
| size class | 大小类 |
| segregated fit | 分离适配 |
| search cost / throughput | 搜索代价 / 吞吐量 |
| memory-related bug | 内存相关错误 |
| wrong allocation size | 分配大小错误 |
| off-by-one error | 差一错误 |
| uninitialized read | 未初始化读取 |
| use-after-free | 释放后使用 |
| double free | 重复释放 |
| memory leak | 内存泄漏 |
| dangling pointer | 悬空指针 |
| AddressSanitizer / LeakSanitizer | 地址消毒器 / 泄漏消毒器 |
| leak checker (valgrind / leaks) | 泄漏检查工具 |
| calloc (zero-initialized) | calloc(清零分配) |