Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 1 (Aug 25), slide deck
01-overview. Reading: CS:APP3e chapter 1. Lab: L0 (cprogramminglab) is handed out. Sources: the public Fall 2026 slides and the CS:APP textbook. The five runnable experiments and all numbers in this lecture were written for these notes and run on the author’s machine (Apple M4 Pro, arm64, Apple clang 21); where behavior is architecture-specific the programs were also cross-compiled to x86-64 and run under Rosetta 2. They do not reproduce what was shown in class. Code:code/lecture01/. Reading time: ~70 minutes for the prose; ~30 more if you run and read every demo.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Say, in one sentence, what makes 15-213 different from your other CS courses, and why a working programmer benefits from it.
- State the five “realities” that organize the whole course, and give one concrete, runnable example of each.
- Explain why an
intis not a mathematical integer and afloatis not a real number, and predict when each abstraction leaks. - Explain why a programmer who will “never write assembly” still must be able to read it.
- Explain why memory is neither protected nor flat, and how that produces both silent wrong answers and 10–100× performance swings.
- Place this course in the CS/ECE curriculum and know which lab exercises which idea.
0.2 Prerequisites and scope
- Prerequisite: you can write basic C — variables,
if/while/for, functions, arrays, pointers,malloc/free, and compile withgcc/clang. If that feels shaky, Lab 0 and the C bootcamp are your refresher; K&R is the reference. - Scope of this lecture: it is a map of the territory, not the territory. Every claim here is unpacked in a later lecture; the job today is to make you want the unpacking by showing five short programs whose behavior contradicts the mental model most beginners carry.
- Not in scope today: the details of two’s complement (Lecture 2), the x86-64 instruction set (Lectures 3–6), cache geometry (Lectures 9–10), and so on. We only open the doors.
0.3 Section → code map
| Section | Idea | Demo in code/lecture01/ |
|---|---|---|
| §2 | ints are a ring; floats are ordered-but-rounded | 01_ints_are_not_integers.c, 02_floats_are_not_reals.c |
| §3 | what runs is the assembly, not your source | 05_you_have_to_know_assembly.c (+ make asm) |
| §4 | no memory protection; bugs act at a distance | 03_memory_referencing_bug.c (+ make asan/make ubsan) |
| §5 | performance is more than big-O | 04_locality_and_the_memory_wall.c |
0.4 Notation
0x...is hexadecimal.2^31means 2 to the 31st power.INT_MAXis the largest 32-bit signed int,2^31 − 1 = 2147483647.- “arm64” (a.k.a. AArch64, Apple Silicon) and “x86-64” (a.k.a. AMD64, Intel/AMD 64-bit) are the two CPU architectures these notes run on. CS:APP uses x86-64.
- A cache line is the fixed-size chunk (64 bytes on x86-64, 128 on the M4) that memory moves in.
1. Why a whole course on “computer systems” — for programmers?
1.1 The one-sentence answer
By understanding how the machine underneath actually executes your program, stores your data, and talks to other machines, you become a more effective programmer: your code is faster, more robust, and less buggy, and you are ready for the systems courses that build on this one (operating systems, compilers, networks, architecture, security).
That is the thesis on slide 6 of the real lecture, and it is worth taking seriously, because it is not obvious. You have spent your previous courses learning abstraction: an int is an integer, a list is a sequence, a function is a black box with a signature, big-O tells you how fast it is. Abstraction is the single most powerful idea in computer science — it lets you build enormous systems by ignoring details. So why would a good course spend a semester tearing abstractions open?
1.2 The motivation: abstractions leak, and the leaks are where you live
Here is the intuition. An abstraction is a promise: “treat this int as an integer and you’ll be fine.” The promise is kept almost always. But every abstraction in a real computer is built on a finite, physical mechanism — a fixed number of bits, a limited amount of memory, a real clock — and when you push against the edge of that mechanism, the promise breaks. The places where it breaks are exactly:
- where your hardest bugs live (the program works on small inputs and corrupts memory on large ones);
- where your security holes live (an attacker deliberately pushes past the edge);
- where your performance is won or lost (two algorithmically identical programs differ 100× because one respects the memory mechanism and one doesn’t).
A builder-centric course (“design a CPU”, “write an OS”, “build a compiler”) teaches you to construct the mechanism. 15-213 is programmer-centric: it teaches you just enough about the mechanism to use the abstraction fully and know where it leaks. You will not build an OS; you will understand processes well enough to write a shell. You will not design a CPU; you will read its assembly well enough to defuse a “binary bomb” and to make a loop 4× faster.
1.3 The shape of the whole course: five realities
The real Lecture 1 frames the course as five “realities” — five ways the comfortable abstraction differs from the machine. They are the backbone of these notes and of the course:
| # | The comfortable abstraction | The reality | Lectures |
|---|---|---|---|
| 1 | integers and real numbers | fixed-width two’s complement and IEEE floating point | 1–2, 15 |
| 2 | “statements that just run” | x86-64 instructions on registers and a stack | 3–6 |
| 3 | one flat, infinite, safe memory | a managed, unprotected hierarchy | 9–14 |
| 4 | speed = big-O | constant factors and the memory system dominate | 10, 15 |
| 5 | “my program computes, alone” | it does I/O, runs beside others, and talks over networks | 16–25 |
The rest of this lecture gives one runnable experiment for each. Run them as you read (cd code/lecture01 && make run); the point of Lecture 1 is to feel each leak, not just read about it.
2. Reality #1 — Ints are not integers, floats are not reals
2.1 Intuition: a number line with a last bit
Think about how you’d store a number in a box that holds exactly 32 switches (bits). There are only 2^32 ≈ 4.3 billion distinct patterns, so your box can hold only 4.3 billion different values — not infinitely many. The designers had two choices to make: which 4.3 billion numbers, and what happens when arithmetic falls off the end.
For a C int the answer is two’s complement: the values −2^31 … 2^31 − 1 arranged not on a line but on a circle — add 1 to the top value (INT_MAX) and you wrap around to the bottom (INT_MIN). For a C double the answer is IEEE 754 floating point: a sign, an 11-bit exponent (scale) and a 52-bit fraction (precision), giving ~15–17 significant decimal digits but with a gap between representable values that grows as the numbers get bigger.
These two designs leak in opposite ways, and seeing the contrast is the whole lesson.
2.2 Integers leak by overflow — but they stay a “ring”
Run 01_ints_are_not_integers.c. Three things come out:
(a) x*x can be negative. The program computes:
40000 * 40000 = 1600000000 (>= 0)
50000 * 50000 = -1794967296 (!!! NEGATIVE !!!)
Why? 50000 * 50000 = 2.5 × 10^9, which is larger than INT_MAX ≈ 2.1 × 10^9. The true product doesn’t fit, so it wraps around the circle into the negative half. This is the slide-8 example from the real lecture, and it is a genuine source of security bugs: a size computed as width * height can wrap to a small or negative number, and a later malloc of that size under-allocates.
(b) Integers are still associative. You might expect that once arithmetic can overflow, the usual algebra falls apart. It does not:
x=INT_MAX, y=1, z=-1
(x+y)+z = 2147483647
x+(y+z) = 2147483647
equal? YES
Even though x+y overflows in the left expression, the final answers match. Mathematicians call a structure where +, −, × wrap but still obey commutativity, associativity and distributivity a ring, and C’s unsigned and two’s-complement integers form one exactly. The wrap is deterministic, not random, so the laws survive. Hold onto this — it is the mirror image of what floats do.
(c) Overflow is just arithmetic modulo 2^32.
INT_MAX + 1 = -2147483648 (= INT_MIN)
INT_MIN - 1 = 2147483647 (= INT_MAX)
“Wrap around the circle” stated precisely: results are taken mod 2^32.
One crucial caveat (foreshadowing §3). The C standard says signed overflow is undefined behavior — the compiler is allowed to assume it never happens. The clean wrap above is what the hardware does; to observe it reliably the demo computes through
volatilevalues and is built with-fwrapv. Without that, an optimizer may “prove” thatx*x ≥ 0or thatx+1 > xand silently change your program. We make that very thing happen in §3.
2.3 Floats leak by rounding — and lose associativity
Now run 02_floats_are_not_reals.c. It is the deliberate opposite of the integer demo.
(a) Float addition is not associative — the famous example from slide 8:
x=1e20, y=-1e20, z=3.14
(x+y)+z = 3.1400000000000001 bits=0x40091eb851eb851f
x+(y+z) = 0 bits=0x0000000000000000
equal? NO
Read it carefully. In (x+y)+z, 1e20 + (−1e20) = 0 exactly, then 0 + 3.14 = 3.14. In x+(y+z), we first compute −1e20 + 3.14; but at the scale of 10^20 the gap between representable doubles is far larger than 3.14, so the sum rounds right back to −1e20 — the 3.14 is annihilated — and then 1e20 + (−1e20) = 0. The order of operations changed the answer, because rounding happens after every single operation, and when you round matters. The raw bit patterns are printed so you can see this is exact, deterministic rounding, not noise.
(b) But floats keep x*x ≥ 0:
(1e+300)^2 = inf (>= 0)
(3.14)^2 = 9.8596 (>= 0)
Overflow produces +inf, never a wrapped negative. Floating point is an ordering structure: it respects sign and monotonicity even when it overflows. So it keeps the property integers lose (sign on overflow) and loses the property integers keep (associativity). That symmetry is the point of pairing the two demos.
(c) 0.1 + 0.2 ≠ 0.3:
0.1 + 0.2 = 0.30000000000000004
0.3 = 0.29999999999999999
0.1, 0.2, 0.3 are each infinite repeating fractions in binary (just as 1/3 is in decimal), so each is already rounded the moment you write it, before any arithmetic. This is why you must never compare floats with ==; compare |a − b| against a small tolerance.
2.4 Why this matters
- Correctness: overflowing sizes, off-by-one loop bounds that wrap, money stored in floats,
==on floats — all classic, shipped-to-production bugs. - Security: integer-overflow-into-
mallocis a whole class of exploits (Lecture 6). - Compilers: because signed overflow is undefined, the optimizer reasons about your arithmetic in ways that can surprise you (§3, and Lecture 15). Knowing which laws hold (the integer “ring”, the float “ordering”) tells you which optimizations are legal.
Lecture 2 makes all of this precise: bit representations, unsigned vs signed, conversion rules, shifting, and why two’s complement was chosen (one representation of zero, −x = ~x + 1, and the same adder hardware for signed and unsigned).
3. Reality #2 — You’ve got to know assembly
3.1 Intuition: the compiler is a very literal, very clever translator
You write C; the CPU runs machine code — a long list of tiny instructions that move bytes between registers and memory and do one arithmetic step at a time. In between sits the compiler, whose job is to translate your C into machine code that produces the same observable behavior. The key word is “observable”: the compiler is free to do anything at all, as long as the program’s outputs look right. It uses that freedom aggressively — and that is exactly why you must be able to read the result.
The ISA (instruction set architecture) is the contract: it lists the instructions, registers and rules the hardware promises to honor. x86-64 and arm64 are two different ISAs with the same job. You will “never write assembly” in the sense of composing whole programs in it — the compiler is better and more patient than you. But you must be able to read it, for four reasons the real lecture lists: debugging behavior in the presence of bugs, tuning performance, understanding security exploits, and writing system software (a compiler’s output, an OS’s context switch, a device driver).
3.2 Experiment: the assembly is smarter than your source
Run 05_you_have_to_know_assembly.c (via make run, which runs it at both -O2 and -O0), then make asm to see the generated instructions.
Part 1 — a loop that is not a loop. The C says “add up 0 + 1 + … + 1999999999” with a two-billion-iteration loop. At -O2:
Part 1: sum_to_n(2000000000) = 1999999999000000000 in 0.000 ms
Zero milliseconds for two billion additions? Look at the assembly (make asm):
arm64 sum_to_n: sub x8,x0,#1 ; mul x10,x8,x9 ; umulh x9,x8,x9 ; extr ... ; ret
The compiler recognized that the loop computes the closed form n·(n−1)/2 and replaced the entire loop with one multiply (mul/umulh give the 128-bit product, extr does the /2). What runs is nothing like what you wrote. At -O0 the same source keeps the real loop and takes ~1.5 seconds — the author measured 1548 ms. “Number of C statements” tells you nothing about speed; the assembly does.
Part 2 — the same C, a different answer. The function inc_gt(x) returns x + 1 > x. Over real integers that is always true. Run it on INT_MAX:
-O2: inc_gt(INT_MAX) = 1
-O0: inc_gt(INT_MAX) = 0
The answer changed with the optimization level. Why? INT_MAX + 1 overflows, and signed overflow is undefined behavior (§2.2). At -O2 the compiler is allowed to assume overflow never happens, so it “proves” x + 1 > x is always true and compiles the whole function to a constant:
x86-64 inc_gt @ -O2: movl $1, %eax ; ret # just returns 1, ignores x
x86-64 inc_gt @ -O0: addl $1,%eax ; cmpl ; setg # actually compares -> 0 at INT_MAX
arm64 inc_gt @ -O2: mov w0, #1 ; ret
This is not a toy curiosity — it is why real programs that rely on signed overflow behave differently across compilers and flags, and why §2.2’s integer demo had to be coaxed with volatile and -fwrapv. You could stare at the C forever and not see it; you must read the assembly.
3.3 Why this matters, and where it goes
- Debugging: when a program misbehaves only at
-O2, or only in release builds, the cause is usually undefined behavior the optimizer exploited. Reading the assembly (or running UBSan, §4) finds it. - Performance (Lecture 15): to make code fast you must see what the compiler did and did not do — did it keep the load in the loop? did it vectorize? did it use a
cmovinstead of a branch? - Security (Lecture 6): buffer-overflow and return-oriented exploits are written in the machine model; you cannot understand or defend them from C alone.
- The labs:
bomblab(Lectures 3–6) is literally “read x86-64 disassembly in gdb to defuse a bomb”;attacklabis “exploit the machine model”.
Lectures 3–6 teach you to read x86-64 fluently: registers and mov, addressing modes, condition codes and jumps, the call stack, and data layout.
4. Reality #3 — Memory matters, and it is not flat
There are two separate shocks here. First, C gives your program no memory protection, so a small mistake can corrupt unrelated data with effects felt far away (“action at a distance”). Second, memory is not uniform — it is a hierarchy, and where your data sits decides your speed (that second shock is Reality #4, §5). This section shows the first.
4.1 Intuition: C hands you the raw address space and trusts you
In C, an array is just a base address plus arithmetic; a[i] means “the bytes at address_of_a + i*sizeof(element)”. There is no check that i is in range. If you write past the end, C simply writes — into whatever happens to be next in memory. Whether that is harmless, corrupts a value, or crashes depends entirely on what the compiler happened to put next to your array, which depends on the compiler, the optimizer and the CPU. The real lecture calls the result “system specific”, and that phrase is the whole lesson.
4.2 Experiment: a bug that corrupts a neighbor
Run 03_memory_referencing_bug.c. It is Bryant & O’Hallaron’s own example. The struct is laid out in memory as:
offset 0 : a[0] (4 bytes)
offset 4 : a[1] (4 bytes) <- the array ends here; valid indices are 0 and 1
offset 8 : d (8 bytes, a double)
fun(i) sets d = 3.14 and then writes a[i] = 2^30. For i = 0,1 that is legal. For i ≥ 2 it writes outside the array. Because any index past 1 can crash the whole program, the demo runs each i in a sacrificial child process (via fork) so one crash doesn’t stop the sweep — itself a preview of Lectures 16–17. On the author’s arm64 build:
i= 0 fun(i) = 3.14
i= 1 fun(i) = 3.14
i= 2 fun(i) = 3.1399998664856 <- d is now CORRUPTED, but no crash, no warning
i= 3 fun(i) = 2.00000061035156 <- d corrupted differently
i= 4..24 fun(i) = 3.14 <- writes land in the CALLER's stack frame; no visible effect here
Indices 2 and 3 write into the 8 bytes of d, so fun returns a wrong number — silently. No crash, no warning, just a corrupted answer. This is the dangerous case: not a loud failure but a quiet lie.
Now the “system specific” part. Cross-compile the same source to x86-64 and run it under Rosetta 2 (make x86):
i= 6 killed by signal 11 (Segmentation fault)
i= 7 killed by signal 11 (Segmentation fault)
Same code, different CPU, different outcome. The reason is visible in the assembly, and it is a first taste of Lecture 5:
- x86-64. The
callinstruction pushes the return address onto the stack, and the compiler saves the old frame pointer%rbpjust below it.ssits directly under those two. Soa[4], a[5](bytes 16–23 pasts) overwrite the saved%rbp— this caller happens not to need it again, so nothing breaks — anda[6], a[7](bytes 24–31) overwrite the return address. Whenfunexecutesret, it jumps to the garbage address, and the kernel kills the process with SIGSEGV. This is exactly the “critical state at index 6” picture on the real slide. - arm64.
funis a leaf function (it calls nothing), so its return address stays in the link registerx30and is never stored on the stack. The function’s whole frame is the 16 bytes ofs; writes past it land in the caller’s frame. Here the child process prints and exits right afterfunreturns, so whatever it overwrote is never used again and nothing visible happens. Had the caller kept a live variable there, it would have been silently changed — a different flavor of action at a distance.
The exact index→effect table depends on the ABI and on what each compiler chose to put next to s. That variability is the point: an out-of-bounds write is undefined, and “it worked on my machine” means nothing.
4.3 The cure: make the invisible visible with sanitizers
C won’t bounds-check for you at run time by default, but the compiler can instrument your program to do it. make asan (AddressSanitizer) and make ubsan (UndefinedBehaviorSanitizer) turn the silent horror into a located error:
# make asan ; ./03_memory_referencing_bug.asan 4
ERROR: AddressSanitizer: stack-buffer-overflow ... WRITE of size 4
#0 ... in fun 03_memory_referencing_bug.c:76
[32, 48) 's' <== Memory access at offset 48 overflows this variable
# make ubsan ; ./03_memory_referencing_bug.ubsan 4
03_memory_referencing_bug.c:76:5: runtime error: index 4 out of bounds for type 'volatile int[2]'
Exact file, exact line, exact object. The habit “when in doubt, run it under the sanitizer” is one of the most valuable things this course gives you.
4.4 Why this matters
- C and C++ provide zero memory safety: out-of-bounds reads/writes, invalid pointers, and
malloc/freemisuse are all undefined and can corrupt anything. - The effect is often distant in space and time from the bug (a write here corrupts a variable there, and the symptom appears minutes later), which makes these the hardest bugs to track down without tools.
- The engineering response is twofold: safer languages bounds-check (Java, Python, Rust, …), and in C you lean on tools (ASan, UBSan,
valgrind) and disciplined style (Lecture 8). The memory hierarchy, allocation, and these bug classes fill Lectures 9–14.
5. Reality #4 — Performance is more than asymptotic complexity
5.1 Intuition: moving data is the real cost
Big-O counts operations and assumes each costs the same. On a real machine that assumption is badly wrong, because the CPU is ~100× faster than main memory (DRAM). To hide that gap, the hardware keeps recently- and nearby-used data in small, fast caches, moving memory in 64–128 byte cache lines. Code that reuses data and touches neighbors (good locality) runs out of cache and flies; code that jumps around memory misses the cache and waits on DRAM every step. Two programs with the identical operation count can differ by 100× purely from locality.
5.2 Experiment: same work, 150–230× different time
Run 04_locality_and_the_memory_wall.c.
Row-major vs column-major copy. C stores 2-D arrays row-major: a[i][0], a[i][1], … are adjacent in memory. Copying with the inner loop over columns (j) walks memory in stride 1 (cache-friendly); copying with the inner loop over rows (i) jumps by a whole row (N·4 bytes) each step (cache-hostile). Same number of assignments:
rows (stride 1): 0.31 ms
cols (stride N): 59.6 ms -> ~190x slower, identical ops
Array vs linked list. Sum ~4.2 million longs, stored three ways: a packed array, a linked list laid out in memory order, and a linked list whose nodes are visited in a random order. All do the same N additions:
array : 2.0 ms
list, in order : 1.9 ms
list, shuffled : 464.1 ms -> ~230x slower (another run: 380 ms, 153x)
The shuffled list pays a cache miss into random DRAM on every ->next. This is why a std::vector/array often crushes a linked list in practice even when big-O says they’re equal, and why cache-aware data layout is a real engineering lever.
The absolute milliseconds depend on your machine and its load; the author’s machine was lightly loaded. The ratios (and their direction) are the robust, reproducible lesson — across the author’s runs the column copy stayed at 190–197× and the shuffled list moved between 153× and 233× (DRAM-latency-bound code is the most sensitive to background load), but the direction and the order of magnitude never changed.
5.3 Why this matters
- You optimize at multiple levels: algorithm, data representation, the procedure, and the loop. A better data layout can beat a better big-O.
- To optimize you must measure (time real code) and understand the machine (what the compiler emitted, which level of the hierarchy you’re hitting). Guessing is almost always wrong.
- Lectures 9–10 explain the hierarchy and caches and teach blocking, the technique that turns a memory-bound kernel cache-friendly; Lecture 15 is the dedicated code-optimization lecture.
6. Reality #5 — Computers do more than execute programs (a preview)
The last reality is less a single demo than the entire back half of the course. A real program doesn’t sit alone computing a function; it:
- does I/O — reads and writes files and devices through the operating system (Lecture 18), which is critical to both reliability and performance;
- shares the machine — the OS multiplexes many processes onto a few cores, and hardware/OS events interrupt your program’s control flow asynchronously (exceptional control flow: processes, signals — Lectures 16–17);
- talks over networks — to other machines over unreliable media, which raises concurrency, partial failure and cross-platform issues (Lectures 19–20);
- does things at once — concurrency and parallelism, with their races, deadlocks and the subtle rules of what one core can observe of another (Lectures 21–24).
Each of these is an abstraction with its own leaks, and each has a lab: a Unix shell (tshlab), a web proxy (proxylab), a file system (sfslab). Lecture 25 (“Frontiers”) steps back and shows where all five realities reappear in modern systems (multicore, accelerators, the memory wall, security as a systems problem).
7. Course perspective and roadmap
7.1 Builder-centric vs programmer-centric
Most systems courses are builder-centric: architecture builds a pipelined CPU, OS builds pieces of a kernel, compilers build a compiler, networking simulates protocols. 15-213 is deliberately programmer-centric — “by knowing more about the underlying system, you can be a more effective programmer.” It is the foundation course that those builder courses assume. The payoff is twofold: you write better everyday code, and you can incorporate features that need hooks into the OS (concurrency, signal handling) that higher-level courses take for granted.
7.2 Where it sits in the curriculum
15-213 is the gateway to the systems half of a CS/ECE degree: operating systems, compilers, computer architecture, networks, distributed systems, databases, security, parallel computing. Every one of them assumes you already understand bytes, assembly, the memory hierarchy, processes and concurrency — i.e. this course.
7.3 The labs (the heart of the course, 50% of the grade)
| Lab | Nickname | You build | Exercises |
|---|---|---|---|
| L0 | cprogramminglab | a queue in C (pointers, lists, robust code, a Makefile) | this lecture + C bootcamp |
| L1 | datalab | integer/float puzzles in a restricted C subset | Lecture 2 |
| L2 | bomblab | defuse a binary by reading its disassembly in gdb | Lectures 3–6 |
| L3 | attacklab | code-injection and return-oriented attacks | Lecture 6 |
| L4 | cachelab | a cache simulator; a locality-optimized transpose | Lectures 9–10 |
| L5 | malloclab | your own malloc/free/realloc | Lectures 13–14 |
| L6 | tshlab | a Unix shell with job control and signals | Lectures 16–17 |
| L7 | proxylab | a concurrent caching web proxy | Lectures 18–21 |
| L8 | sfslab | extend a simple file system; parallelism | Lectures 18–19, 24 |
A note on these notes and the course’s academic-integrity policy. The real 15-213 forbids enrolled students from using AI tools or outside solutions on the labs, and these notes respect that: they are self-study material that teaches the ideas and skills each lab rehearses, and they deliberately contain no lab solutions. The demos here are original teaching programs, not lab code. If you are enrolled in 15-213, treat this as you would the textbook or a man page (allowed), not as a source of lab answers (not allowed) — and keep AI tools out of your lab editor as the course requires.
8. How to work in this course
- Build and run everything. Reading about overflow is forgettable; watching
50000*50000print a negative number is not.cd code/lecture01 && make run. - Read the assembly.
make asm,objdump -d,gdb/lldb. The machine never lies about what it does. - Run under the sanitizers.
-fsanitize=address,undefinedcatches a huge fraction of C’s undefined behavior at the exact line. Make it a reflex. - Measure, don’t guess. Time real code; quote one run and note that timing varies. Every number in these notes came from an actual run, labelled with the machine.
- Be honest about surprises. When an experiment contradicts the plan, the code READMEs record it (“Plan vs reality”). Reality #4’s dead-store elimination and Reality #2’s compile-time constant folding both surprised this author mid-write; both are documented.
Summary
- 15-213 is the programmer-centric systems course: understand the machine well enough to use its abstractions fully and to know where they leak.
- The course is organized around five realities, each a gap between a comfortable abstraction and the physical mechanism:
- Ints are not integers, floats are not reals. Integers are a finite ring (wrap on overflow, but associative); floats are ordered but rounded (keep sign, lose associativity).
50000*50000 < 0;(1e20+-1e20)+3.14 ≠ 1e20+(-1e20+3.14). - You’ve got to know assembly. The compiler translates and optimizes aggressively; what runs is the machine code, not your source. A loop can become a multiply; undefined behavior can change the answer between
-O0and-O2. - Memory is unprotected and not flat. C does no bounds checking; an out-of-bounds write corrupts a neighbor “at a distance”, with system-specific results. Sanitizers make it visible.
- Performance is more than big-O. Locality in the memory hierarchy swings identical-op-count code by 150–230× in these demos.
- Computers do I/O, concurrency and networking — the back half of the course.
- Ints are not integers, floats are not reals. Integers are a finite ring (wrap on overflow, but associative); floats are ordered but rounded (keep sign, lose associativity).
- Everything above is a preview; Lectures 2–25 unpack each reality, and the labs make you live inside it.
Common pitfalls (for the ideas in this lecture)
- Assuming
intarithmetic can’t overflow. Size/length computations (w*h,n+1) wrap silently; validate before allocating or indexing. - Comparing floats with
==. Use a tolerance; never testa == bfor computed doubles. - Thinking undefined behavior means “it’ll just wrap/segfault”. UB lets the optimizer do anything, including deleting your checks or changing results (§3). Don’t rely on it; build with
-fwrapv/sanitizers if you must observe hardware behavior. - Trusting “it worked on my machine”. Out-of-bounds and other UB are system-specific (§4.2). Different compiler, flags or CPU can turn a silent pass into a crash.
- Judging performance by operation count. Measure; respect locality (§5).
git add ./git commit -a. The real course warns against these — commit specific files so you never hand in stray edits (and so your commit history is clean).
Exercises
-
Overflow to a wrong allocation. Explain how
int n = width * height; int *p = malloc(n * sizeof(int));can under-allocate even whenmallocsucceeds. What happens next when you writep[width*height-1]?Answer
If `width*height` overflows `int`, `n` can be small or negative. `malloc(n*sizeof(int))` then allocates far too little (or, for negative `n` converted to a huge `size_t`, may fail). Subsequent writes go out of bounds — a classic heap overflow and a real exploit primitive. Fix: use a wide unsigned type and check for overflow before multiplying, or use `calloc`, which checks the multiplication for you. -
Predict the float. Without running, is
(1e16 + 1.0) - 1e16equal to1.0? What about(1e15 + 1.0) - 1e15? Why might they differ?Answer
At `1e16` the gap between neighbouring doubles is 2.0, so `1e16 + 1.0` rounds back to `1e16` and the result is `0.0`. At `1e15` the gap is 0.125, so `1e15 + 1.0` is exactly representable and the result is `1.0`. (Checked on the author's machine: the two expressions print `0` and `1`.) The threshold is `2^53 ≈ 9.0e15`: with a 52-bit fraction, the spacing of doubles is exactly 1.0 between `2^52` and `2^53`, so adding 1 is still exact there; from `2^53` upward the spacing is 2, and `(2^53 + 1) − 2^53` already gives `0`. -
Read the assembly. In
05_you_have_to_know_assembly.c,make asmshowssum_to_nas a multiply at-O2. What single change tomainwould make the compiler instead precompute the whole answer to a constantmov(no multiply)? What change would force it to keep the real loop?Answer
Pass a compile-time constant (`sum_to_n(2000000000L)` directly, without the `volatile`) and the compiler constant-propagates the entire result → a single `mov` of `1999999999000000000`. To force the real loop, make the body depend on something it cannot reduce to a closed form (e.g. `s += data[i]` from an unknown array, or add an early-exit condition), or compile at `-O0`. -
Make the bug segfault on purpose. On your machine, run
03_memory_referencing_bugand note which indices (if any) crash. Thenmake x86(Apple Silicon) or compile with a different-Olevel. Do the crashing indices move? What does that tell you?Answer
They very likely move (on the author's machine arm64 crashed at no index in 0..24, x86-64 crashed at 6–7). The set of "dangerous" indices is a function of stack layout, which the ABI, compiler, optimization level and ASLR all affect. Lesson: out-of-bounds behavior is undefined and non-portable; never reason about *which* corruption you'll get, only that it is a bug. -
Explain the 150–230×. In
04, the in-order linked list is as fast as the array, but the shuffled list is ~150–230× slower. All three doNadditions andNpointer/index steps. Where does that factor come from, in terms of cache lines?Answer
The array and in-order list walk memory sequentially, so each cache line (64–128 B) brings in several elements/nodes and is reused — few misses. The shuffled list visits nodes in random order, so almost every `->next` lands on a different, not-yet-cached line: ~one DRAM miss per node. A DRAM miss costs ~100× a cache hit, which (amortized over the small amount of work per node) shows up as the 150–230× wall-clock gap.
The related lab: L0 (cprogramminglab)
Lab 0 is a C refresher: implement a queue with a singly linked list, handle NULL and empty cases robustly, manage memory with malloc/free (no leaks), and write a Makefile. It touches Realities #1 and #3 directly (pointer bugs, memory management) and sets the tooling habits (sanitizers, make) the rest of the course assumes. The slides say: if L0 takes you more than ~10 hours, reconsider whether you’re ready for the course. These notes don’t provide L0 code; the C bootcamp and K&R are your references.
Further reading
- CS:APP3e chapter 1, “A Tour of Computer Systems” — the textbook version of this lecture.
- CS:APP3e §2.2–2.3 (integers) and §2.4 (floating point) — the precise version of Reality #1, next lecture.
- Recitation 1 (Introduction, Datalab) and Bootcamps 1–2 (Linux/command line/git; debugging & gdb) on the course page — the practical on-ramp.
- David Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic (1991) — the deep version of §2.3.
Preview of Lecture 2 — Bits, bytes and integers
Next we zoom into Reality #1a and make it exact: how bits and bytes encode information, hexadecimal and byte order (endianness), Boolean algebra and the bit-level operators (& | ~ ^) versus the logical ones (&& || !), and the two integer encodings — unsigned and two’s complement — on the number circle. We’ll derive signed/unsigned conversion and its traps (-1 < 0U is false!), sign extension, and the two kinds of shift, and we’ll see why two’s complement is the universal choice (one zero, −x = ~x + 1, and a single adder for both signed and unsigned). That is exactly the machinery Lab 1 (datalab) makes you wield with your hands tied behind your back.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| abstraction / reality | 抽象 / 现实 |
| leaky abstraction | 有漏洞的抽象(抽象泄漏) |
| programmer-centric / builder-centric | 以程序员为中心 / 以构建者为中心 |
| two’s complement | 补码 |
| unsigned / signed integer | 无符号 / 有符号 整数 |
| overflow / wrap-around | 溢出 / 回绕 |
| modular arithmetic | 模运算 |
| ring (algebra) | 环(代数结构) |
| associativity / commutativity / distributivity | 结合律 / 交换律 / 分配律 |
| floating point / IEEE 754 | 浮点数 / IEEE 754 标准 |
| sign / exponent / fraction (mantissa) | 符号位 / 阶码(指数) / 尾数 |
| rounding (round to nearest) | 舍入(就近舍入) |
| monotonicity / ordering structure | 单调性 / 有序结构 |
| undefined behavior (UB) | 未定义行为 |
| optimization level (-O0 / -O2) | 优化级别 |
| instruction set architecture (ISA) | 指令集架构 |
| machine code / assembly | 机器码 / 汇编 |
| compiler / optimizer | 编译器 / 优化器 |
| register | 寄存器 |
| constant propagation / folding | 常量传播 / 常量折叠 |
| dead-store / dead-code elimination | 死存储 / 死代码 消除 |
| memory protection | 内存保护 |
| out-of-bounds access | 越界访问 |
| action at a distance | 远距作用(远程副作用) |
| segmentation fault (SIGSEGV) | 段错误 |
| AddressSanitizer / UndefinedBehaviorSanitizer | 地址消毒器 / 未定义行为消毒器 |
| process / fork | 进程 / 创建子进程 |
| memory hierarchy | 存储层次结构 |
| cache / cache line | 高速缓存 / 缓存行 |
| locality (temporal / spatial) | 局部性(时间 / 空间) |
| DRAM / the memory wall | 动态随机存储器 / 内存墙 |
| row-major order | 行主序 |
| stride | 步长 |
| asymptotic complexity (big-O) | 渐近复杂度(大 O) |
| exceptional control flow | 异常控制流 |
| concurrency / parallelism | 并发 / 并行 |