Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 8 (Sep 17), slide deck
08-design-debugging. Reading: CS:APP3e §9.10–9.12 (common memory bugs) plus the course’s debugging and design material. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and runs the real toolchain on an Apple M4 Pro (macOS, clang 21). valgrind and-fsanitize=memory(the uninitialized-read detector the slides use) are unavailable on arm64 macOS, so the debugging demo finds the bug by method and spec; AddressSanitizer and UndefinedBehaviorSanitizer are available and used. Code:code/lecture08/. Reading time: ~75 minutes; ~20 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Distinguish defect, error and failure, and explain why not every defect causes a visible failure.
- Debug by the scientific method: hypothesis → prediction → experiment → observation → diagnosis → fix → confirm, changing one condition at a time.
- Explain why a bug’s symptom can change with the optimization level or the run, and why “it works at
-O0” proves nothing. - Pick the right tool for a bug class:
-Wall,gdb/lldb, AddressSanitizer, UndefinedBehaviorSanitizer, valgrind. - Use assertions, invariants and contracts to turn silent wrong answers into located crashes, and know when to assert vs defensively check.
- Recognize design habits — modularity, testability, good names and comments — that keep bugs from arising.
0.2 Prerequisites and scope
- Lectures 1–7, especially Lecture 1’s sanitizers and the bug classes seen since: uninitialized data, the memory-referencing bug, a symbol mismatch (Lecture 7), out-of-bounds writes (Lecture 6).
- In scope: the slides’ two halves — debugging (defects/errors/failures, scientific debugging, tools) and design (managing complexity, testability, naming, comments, trusting the compiler) — and CS:APP §9.11’s catalog of C memory bugs.
0.3 Section → code map
| Section | Idea | Demo in code/lecture08/ |
|---|---|---|
| §1 | defect → error → failure | — |
| §2 | scientific debugging (the badfib case) | 01_scientific_debugging.py |
| §3 | why symptoms shift; tools for each bug class | 01_…, 02_tools.py |
| §4 | design: complexity, testability, contracts | 03_contracts.c |
| §5 | communication: naming and comments | — |
1. Defects, errors, and failures
The slides open with a launch failure (Atlas-Centaur) to make the vocabulary precise (CS:APP and the software-engineering literature):
- The programmer creates a defect (also “fault” or “bug”) — wrong code.
- Running it may produce an error — wrong internal state (a bad value in a variable, a wrong branch taken).
- The error may propagate through further computation.
- It may finally cause a failure — a wrong result observed at an interface (a wrong output, a crash).
Why is an error not always a failure? Because an error can be masked (overwritten before it matters) or the defect may simply not be triggered on this run. The slides’ picture: some executions never reach the defect; others reach it but the erroneous state never reaches an output. That is exactly why bugs are so slippery — and why “I couldn’t reproduce it” is common. Debugging is the search back from a failure to its defect, through the propagation.
The curse of debugging: a failure tells you only that something is wrong somewhere, possibly far from where the defect lives (Lecture 7’s strong/weak mismatch failed in the caller; Lecture 1’s array bug corrupted an unrelated variable). The rest of the lecture is about doing this search by method instead of luck.
2. Scientific debugging
2.1 The method
The slides frame debugging as science (after Zeller, Why Programs Fail):
- Observe a failure, and know what should happen (the spec).
- Form a hypothesis: a proposed defect that would explain the failure. Prefer the simplest that fits (Occam’s razor), closest to what you just changed.
- Predict: if the hypothesis is right, what will happen under a new condition?
- Experiment: reproduce the failing run with exactly one condition changed (an input, a watch in the debugger, an edit).
- Observe the result factually.
- Refute or refine the hypothesis; repeat until a hypothesis survives — the diagnosis.
- Fix, then confirm the fix resolves the failure and keeps the working cases.
Two discipline rules the slides stress: change one thing at a time, and do not proceed past the first bug — a second change muddies which one mattered.
2.2 The badfib case
The slides’ buggy Fibonacci:
int fib(int n) {
int f, f0 = 1, f1 = 1; // f is never initialized
while (n > 1) { n = n - 1; f = f0 + f1; f0 = f1; f1 = f; }
return f;
}
It prints fib(9)…fib(2) correctly but fib(1) is wrong. 01_scientific_debugging.py PART A reproduces it:
buggy build at -O0: fib(9)..fib(2) are all correct; fib(1) is wrong.
fib(1) equals the spec value 1? no
fib(1) the same on three runs? no
Three runs give three different fib(1) values. An unstable result is the signature of reading uninitialized memory: the returned value is whatever was left on the stack. (The demo pins it afterward with -ftrivial-auto-var-init=pattern, which fills uninitialized locals with 0xAA bytes, so the experiments are reproducible — fib(1) then reads -1431655766. Reproducible, but still not 1.)
First, the spec: the first Fibonacci number is 1, so fib(1) should be 1. It is not, so this is a failure, not merely surprising output.
2.3 Three hypotheses, three experiments
Reading the code (slides “Constructing a Hypothesis”) suggests three possible defects. PART B runs each as a one-change experiment:
hypothesis: 1. call order matters
experiment: call fib(1) first and alone
observation: fib(1) = -1431655766 (still wrong)
hypothesis: 2. loop test `n > 1` is wrong
experiment: change it to `n >= 1`
observation: breaks a working case: fib(2)=3, should be 2
hypothesis: 3. `f` is uninitialized
experiment: initialize `int f = 1;`
observation: ALL correct, including fib(1)=1
- Hypothesis 1 (the failure depends on the order of calls in
main) is refuted:fib(1)called first is still wrong, because forn = 1the loop body never runs regardless of order. - Hypothesis 2 (
n > 1should ben >= 1) does makefib(1)return a value, but breaksfib(2)and up — it computes the wrong sequence. A fix that creates new failures is not a fix. (A prediction can double as a fix, but only if you confirm the working cases too.) - Hypothesis 3 (
fis uninitialized) is confirmed: forn = 1the loop never executes, so the uninitializedfis returned;int f = 1;fixesfib(1)and keeps every working case. This is the diagnosis and the fix.
Beware the post hoc fallacy (slides “Diagnosis”): a change that makes the symptom vanish is not automatically the fix — understand why the defect and the fix relate. Here we do: the loop skip explains it exactly.
3. Why symptoms move, and the tools that pin them
3.1 “Works at -O0” proves nothing
Reading uninitialized memory is undefined behavior, and a compiler may assume undefined behavior never happens. So the same badfib behaves differently at different optimization levels: at -O0 it returns stack garbage; at -O2 it may return a value or trap outright. The symptom also varies with the compiler version and the surrounding code. The lesson (slides, and CS:APP throughout): a program that “works” under one build has not been shown correct — undefined behavior is a bug even when today’s output looks fine.
3.2 The brute-force tools, and sanitizers
When reading and reasoning stall, tools generate evidence. The slides show valgrind catching badfib’s uninitialized read (naming the line), and note it reports differently at -O3 vs -O0. On this machine valgrind and the MemorySanitizer are unavailable, but AddressSanitizer and UndefinedBehaviorSanitizer are, and 02_tools.py shows them catching a range of bugs that otherwise hide:
heap-oob (write one past a heap array)
plain -O0: ran without crashing -- bug hidden
ASan: heap-buffer-overflow (bugs.c:23)
use-after-free (read freed heap memory)
plain -O0: ran without crashing -- bug hidden
ASan: heap-use-after-free (bugs.c:33)
signed-overflow (INT_MAX + 1)
plain -O0: ran without crashing -- bug hidden
UBSan: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int' (bugs.c:46)
oob-index (array[10] on a 4-element array)
plain -O0: ran without crashing -- bug hidden
UBSan: index 11 out of bounds for type 'int[4]' (bugs.c:59)
Every plain build ran without crashing, yet every one has a real bug: “it didn’t crash” is not “it’s correct”, the corruption is just silent. Each tool targets a class:
| Tool | Catches | How |
|---|---|---|
-Wall -Wextra (compile time) | many mistakes: unused/uninitialized vars, sign confusion, format strings | static analysis, free |
AddressSanitizer (-fsanitize=address) | out-of-bounds, use-after-free, leaks | instruments every memory access |
UndefinedBehaviorSanitizer (-fsanitize=undefined) | overflow, bad shifts, bad indices, misaligned access | instruments undefined operations |
| valgrind / memcheck (Linux) | the ASan memory classes without recompiling, plus uninitialized reads | runs the binary on a synthetic CPU |
gdb / lldb | anything, interactively: breakpoints, watchpoints, backtraces | a debugger |
The habit the slides push: build and test under these tools from the start. “I can’t reproduce it” often means “I haven’t run the right tool.”
3.3 Observation discipline
Two cautions from the slides’ “Observation” slide:
- Don’t interfere. A
printfadded to observe a bug can change timing or memory layout and hide it (a “heisenbug”). Prefer a debugger watchpoint or a sanitizer that observes without perturbing. - Proceed systematically. Change conditions incrementally so each observation ties to one change; never move past the first bug you find.
4. Design: fewer bugs by construction
Debugging finds bugs; good design stops them arising. The slides’ second half is about managing complexity.
4.1 Break a task into testable pieces
The slides’ example decomposes a cache-simulator access (which you will write in cachelab, Lecture 10) into independent steps:
convert address into tag / set index / block offset
look up the set
check whether the tag matches a line in the set -> hit
on a miss: find the LRU line, evict it, read the new line
update LRU; update the dirty bit if the access was a store
Each step is small, has a clear input and output, and can be tested on its own. A design that is hard to test is usually too tangled; making it testable forces modularity. 03_contracts.c applies this to a binary search, split into is_sorted and bsearch_int, each checkable independently.
4.2 Contracts: preconditions, postconditions, invariants
A contract states what a function requires and promises:
- Precondition: what the caller must guarantee (
bsearch_intrequires a sorted array). - Postcondition: what the function delivers (returns an index whose element equals the key, or −1).
- Invariant: something true throughout (the search bounds satisfy
lo ≤ mid ≤ hi).
Writing these down is an act of design and documentation as much as verification (slides “Designs need to be testable”): it forces you to understand the code. Checking them with assertions makes a violation fail at the boundary, loudly and located, instead of becoming a silent wrong answer that surfaces far away. Demo 03 PART B calls bsearch_int on an unsorted array (a broken precondition), in a forked child so the demo survives:
calling bsearch_int on an UNSORTED array {5,1,4,2,3} ...
Assertion failed: (is_sorted(a, n)), function bsearch_int, file 03_contracts.c, line 58.
the child was killed by signal 6 (SIGABRT from assert): the assertion fired AT THE
CALL, naming the violated precondition ...
The assertion turned a caller’s mistake into an immediate, named failure.
4.3 Assert vs defend
When is a check an assert, and when a run-time validation that returns an error? (Demo 03 PART C.)
- Assert a condition that should be impossible if the code is correct — a programmer error (a precondition a caller must meet). Assertions document intent and catch bugs in development, and they compile away under
-DNDEBUG, so they cost nothing in release builds. - Defensively validate input that can legitimately be bad at run time — data from a file, the network, or a user. Reject it and report failure (
bsearch_checkedreturnsok = false), do not crash.
Confusing the two is a common design error: a server must not assert that a network packet is well-formed (an attacker will oblige by crashing it), and ordinary code should not clutter itself defending against conditions its own logic guarantees.
4.4 Trust the compiler
The slides’ “Trust the Compiler!” point: write clear code and let the compiler optimize it (Lectures 4–5 showed -O1/-Og turning recursion into loops and index arithmetic into pointers). Hand-optimized, tangled code is harder to read, to test and to debug, and rarely beats the compiler. Turn the warnings on (-Wall -Werror) and treat them as errors; many defects (the uninitialized f among them, on compilers that warn) are caught for free at compile time.
5. Communication: naming and comments
The slides spend their final third on readability, because code is read far more than written and most debugging time is spent understanding code.
Naming (slides “Naming is understanding”): a good name describes meaning in the problem’s own vocabulary. Use dictionary words, not abbreviations you will not recognize in a month; avoid single-letter names except for short-lived loop indices; keep names a sensible length and word count; use opposites precisely (begin/end, first/last, not begin/stop). A name you cannot choose well is often a sign you do not yet understand the thing — naming is understanding.
Comments (slides “Do/Don’t Comments”): do not narrate what the code already says (i++; // add one to i); that is noise, and it rots. Do say why — the intent, the non-obvious constraint, the reason a workaround exists, the invariant that must hold. If a comment is needed to explain what awkward code does, the better fix is usually to rewrite the code. (These notes’ own code follows this: the [Idea]/[Edge cases]/[Systems link] tags say why and how, not what.)
Summary
- A defect may cause an error (wrong state) which may cause a failure (wrong result at an interface). An error can be masked or untriggered, which is why bugs hide and surface far from their cause.
- Debug scientifically: observe the failure against the spec, hypothesize the simplest defect, predict, experiment with one changed condition, observe, and refine to a diagnosis; then fix and confirm — including the previously-working cases. Do not proceed past the first bug.
- A bug’s symptom can change with the optimization level, the run, or the compiler, because undefined behavior lets the compiler assume it never happens. “Works at
-O0” is not “correct”. - Use the right tool:
-Wallat compile time, ASan for memory safety, UBSan for undefined arithmetic, valgrind (Linux) without recompiling, a debugger for anything. Build tests to run under them. - Design for testability: break a task into small pieces with clear contracts (preconditions, postconditions, invariants). Assert programmer errors (they compile away in release); defensively validate untrusted input.
- Write for the reader: name things in the problem’s vocabulary, and comment the why, not the what.
Common pitfalls
- Debugging by random edits. Changing several things, or guessing past the first bug, loses track of cause and effect. One hypothesis, one experiment.
- Accepting a fix that passes only the failing case. Re-run the working cases; a “fix” like
badfib’sn >= 1can break them. - Trusting a
-O0run. Undefined behavior may be benign at-O0and catastrophic at-O2. Compile with warnings and sanitizers. printf-debugging a timing/memory bug. Theprintfcan move the bug. Use a watchpoint or a sanitizer.- Asserting on untrusted input. An
asserton a network packet is a denial-of-service waiting to happen; validate and reject instead. - Comments that restate the code. They add nothing and drift out of date; comment intent, invariants and surprises.
Exercises
-
Vocabulary. A function computes a running average and occasionally returns a value slightly too high, only for inputs longer than 1000 elements. Identify the likely defect, error and failure.
Answer
Defect: e.g. an accumulator that overflows or loses precision for large sums. Error: the accumulator holds a wrong value mid-computation. Failure: the returned average is too high — observed only when inputs are large enough to trigger the defect and the error reaches the output. -
One change. You suspect a bug is in function
g, called byf, called bymain. You simultaneously rewritegand add bounds checks inf, and the failure disappears. Why is this unsatisfying?Answer
Two conditions changed at once, so you cannot tell which fixed it — maybe neither addressed the real defect and the behavior shifted by luck. Change one thing, confirm, then the other. You also do not yet understand *why* the fix works (post hoc fallacy). -
Optimization-dependent. A loop
for (int i = 0; i <= n; i++) sum += a[i];on ann-element array seems fine at-O0but crashes at-O2. What is the defect and why the difference?Answer
`i <= n` reads `a[n]`, one past the end — out of bounds. At `-O0` the stray read may hit mapped memory and be harmless; at `-O2` layout and vectorization change what `a[n]` touches, so it faults. The fix is `i < n`; ASan would name it immediately. -
Which tool? Match each bug to the best tool: (a) a format-string typo
printf("%d", x)wherexis adouble; (b)free(p); ... *p; (c)1 << 33on a 32-bit int; (d) an intermittent wrong result you cannot reproduce.Answer
(a) `-Wall` at compile time (format/argument mismatch). (b) AddressSanitizer or valgrind (use-after-free). (c) UndefinedBehaviorSanitizer (shift ≥ width). (d) a debugger with a watchpoint, plus sanitizers; and pin nondeterminism (seeds, `-ftrivial-auto-var-init`) to make it reproducible. -
Assert or defend? For each, say whether a precondition
assertor a defensive run-time check is appropriate: (a) a private helper that assumes its index is in range because its only caller guarantees it; (b) a publicparse_headerthat reads bytes from a network socket; (c) asqrt-like function documented to require a non-negative argument.Answer
(a) assert — a caller bug if violated, and it compiles away in release. (b) defensive check — untrusted input will be malformed; reject and return an error. (c) assert if it is an internal contract with trusted callers; a library exposed to arbitrary callers may prefer to return an error/NaN. Judgment depends on who calls it. -
Contract. Write the precondition, postcondition and one loop invariant for a function
int index_of(const int *a, int n, int key)that returns the first index ofkeyina[0..n-1], or −1.Answer
Precondition: `n >= 0` and `a` points to at least `n` ints. Postcondition: returns `i` with `a[i] == key` and `a[j] != key` for all `j < i`, or −1 if `key` is absent. Invariant (linear scan): before examining index `i`, `key` does not appear in `a[0..i-1]`. -
Naming. Improve these names and say why:
int d;(days between two dates),bool flag;(whether the user is an admin),void proc();(sends a confirmation email).Answer
`days_between` / `num_days`, `is_admin`, `send_confirmation_email`. Each states meaning in the problem's vocabulary, so the code reads as prose and reviewers catch wrong uses (`if (flag)` vs `if (is_admin)`). -
Comment. Rewrite this comment to be useful:
x = x & (x - 1); // clear a bit.Answer
Say *which* bit and *why*: `// clear the lowest set bit of x (Lecture 2); loop body counts set bits`. The original restates the operation without the intent; the useful version names the trick and its purpose.
The related lab
There is no lab released specifically for this lecture, but its method underlies all of them. bomblab (in progress) is pure scientific debugging with gdb. cachelab (Lecture 10) rewards the decomposition in §4.1 and writing your own test traces. malloclab (Lectures 13–14) is nearly impossible without AddressSanitizer/valgrind discipline and invariants on the heap structure. The habits here — reproduce, hypothesize, change one thing, assert your invariants, run the sanitizers — are the labs’ survival kit.
Further reading
- CS:APP3e §9.11 (common memory-related bugs in C) — a catalog of the classes Demo 02 triggers.
- A. Zeller, Why Programs Fail: A Guide to Systematic Debugging — the source of the scientific-debugging framing.
- The AddressSanitizer and UndefinedBehaviorSanitizer documentation; the valgrind manual;
man gdb/ the LLDB tutorial. - B. Kernighan and R. Pike, The Practice of Programming — naming, comments, testing and debugging, in the same spirit as the slides’ design half.
Preview of Lecture 9: The memory hierarchy
Units I–II treated memory as a flat, uniform array. Lecture 9 begins Unit III by taking that abstraction apart. SRAM, DRAM, disks and SSDs differ in speed by orders of magnitude, and the CPU–memory gap has widened for decades. The saving grace is locality — programs tend to reuse recent data (temporal) and nearby data (spatial) — which lets a hierarchy of caches behave almost like one big fast memory. You will measure the “memory mountain”, see read throughput swing with working-set size and stride, and learn to eyeball a loop’s locality. It is where “performance is more than big-O” (reality 4) becomes concrete.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| defect / fault / bug | 缺陷 / 故障 / 错误(bug) |
| error (wrong state) | 错误(错误状态) |
| failure | 失效(对外可见的错误结果) |
| error propagation | 错误传播 |
| masking (an error) | 掩盖(错误被覆盖) |
| scientific debugging | 科学调试法 |
| hypothesis / prediction | 假设 / 预测 |
| experiment / observation | 实验 / 观察 |
| diagnosis | 诊断 |
| Occam’s razor | 奥卡姆剃刀 |
| post hoc fallacy | 后此谬误(相关非因果) |
| regression (confirming a fix) | 回归(确认修复) |
| undefined behavior | 未定义行为 |
| optimization level | 优化级别 |
| uninitialized variable | 未初始化变量 |
| heisenbug | 海森堡 bug(观察即干扰) |
| AddressSanitizer (ASan) | 地址消毒器 |
| UndefinedBehaviorSanitizer (UBSan) | 未定义行为消毒器 |
| valgrind / memcheck | 内存检查工具 |
| debugger (gdb / lldb) | 调试器 |
| breakpoint / watchpoint | 断点 / 观察点 |
| complexity management | 复杂度管理 |
| modularity | 模块化 |
| testable design | 可测试设计 |
| contract | 契约 |
| precondition / postcondition | 前置条件 / 后置条件 |
| invariant | 不变式 |
| assertion (assert) | 断言 |
NDEBUG | 关闭断言的宏 |
| defensive programming | 防御式编程 |
| naming | 命名 |
| comment (why vs what) | 注释(说明“为什么”而非“做什么”) |