Lecture 8 · Design and debugging

Introduction to Computer Systems · Lecture 08。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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:

  1. Distinguish defect, error and failure, and explain why not every defect causes a visible failure.
  2. Debug by the scientific method: hypothesis → prediction → experiment → observation → diagnosis → fix → confirm, changing one condition at a time.
  3. Explain why a bug’s symptom can change with the optimization level or the run, and why “it works at -O0” proves nothing.
  4. Pick the right tool for a bug class: -Wall, gdb/lldb, AddressSanitizer, UndefinedBehaviorSanitizer, valgrind.
  5. Use assertions, invariants and contracts to turn silent wrong answers into located crashes, and know when to assert vs defensively check.
  6. 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

SectionIdeaDemo in code/lecture08/
§1defect → error → failure—
§2scientific debugging (the badfib case)01_scientific_debugging.py
§3why symptoms shift; tools for each bug class01_…, 02_tools.py
§4design: complexity, testability, contracts03_contracts.c
§5communication: 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):

  1. The programmer creates a defect (also “fault” or “bug”) — wrong code.
  2. Running it may produce an error — wrong internal state (a bad value in a variable, a wrong branch taken).
  3. The error may propagate through further computation.
  4. 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):

  1. Observe a failure, and know what should happen (the spec).
  2. 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.
  3. Predict: if the hypothesis is right, what will happen under a new condition?
  4. Experiment: reproduce the failing run with exactly one condition changed (an input, a watch in the debugger, an edit).
  5. Observe the result factually.
  6. Refute or refine the hypothesis; repeat until a hypothesis survives — the diagnosis.
  7. 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 for n = 1 the loop body never runs regardless of order.
  • Hypothesis 2 (n > 1 should be n >= 1) does make fib(1) return a value, but breaks fib(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 (f is uninitialized) is confirmed: for n = 1 the loop never executes, so the uninitialized f is returned; int f = 1; fixes fib(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:

ToolCatchesHow
-Wall -Wextra (compile time)many mistakes: unused/uninitialized vars, sign confusion, format stringsstatic analysis, free
AddressSanitizer (-fsanitize=address)out-of-bounds, use-after-free, leaksinstruments every memory access
UndefinedBehaviorSanitizer (-fsanitize=undefined)overflow, bad shifts, bad indices, misaligned accessinstruments undefined operations
valgrind / memcheck (Linux)the ASan memory classes without recompiling, plus uninitialized readsruns the binary on a synthetic CPU
gdb / lldbanything, interactively: breakpoints, watchpoints, backtracesa 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 printf added 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_int requires 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_checked returns ok = 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: -Wall at 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’s n >= 1 can break them.
  • Trusting a -O0 run. Undefined behavior may be benign at -O0 and catastrophic at -O2. Compile with warnings and sanitizers.
  • printf-debugging a timing/memory bug. The printf can move the bug. Use a watchpoint or a sanitizer.
  • Asserting on untrusted input. An assert on 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

  1. 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.

    AnswerDefect: 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.
  2. One change. You suspect a bug is in function g, called by f, called by main. You simultaneously rewrite g and add bounds checks in f, and the failure disappears. Why is this unsatisfying?

    AnswerTwo 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).
  3. Optimization-dependent. A loop for (int i = 0; i <= n; i++) sum += a[i]; on an n-element array seems fine at -O0 but 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.
  4. Which tool? Match each bug to the best tool: (a) a format-string typo printf("%d", x) where x is a double; (b) free(p); ... *p; (c) 1 << 33 on 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.
  5. Assert or defend? For each, say whether a precondition assert or 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 public parse_header that reads bytes from a network socket; (c) a sqrt-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.
  6. 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 of key in a[0..n-1], or −1.

    AnswerPrecondition: `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]`.
  7. 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)`).
  8. Comment. Rewrite this comment to be useful: x = x & (x - 1); // clear a bit.

    AnswerSay *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.

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)注释(说明“为什么”而非“做什么”)
← 返回课程目录