Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 6 (Sep 10), slide deck
06-machine-delta. Reading: CS:APP3e §3.9–3.11 (structures, unions, alignment, memory layout, buffer overflow, and a note on floating-point code). Lab: L3 (attacklab) uses this lecture’s ideas. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes. Structure-access functions are run in Lecture 3’s simulatorx86sim.pyand checked against the real x86-64 machine code (Rosetta 2 on an Apple M4 Pro): 0 disagreements in 65 tests at each optimization level. The alignment, memory-layout and union demos are native C, run on both arm64 and x86-64. A deliberate scope. This lecture treats buffer overflows at the level of concept and defense only. In keeping with the course’s academic-integrity policy, these notes and their code do not construct or simulate an attack (no string that overwrites a return address, no injected code). The experiments show how to write code that cannot overflow, and the protections the compiler and OS already provide. Code:code/lecture06/. Reading time: ~90 minutes; ~30 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Give the offset of each field of a struct, and its total size, using the two alignment rules; and explain why reordering fields can shrink a struct.
- Recognize structure and array-of-structure access in assembly (a field is a fixed offset; the array stride is the full struct size).
- Describe the x86-64 memory layout of a running process, and explain what address-space layout randomization does.
- Explain what a buffer overflow is, why it is dangerous, and what each of the three standard defenses — stack canaries, non-executable stack (NX), ASLR — takes away from it.
- Write input-handling code that cannot overflow, using length-limited library functions and checking for truncation.
- Explain what a union is, when it is safe (a tagged sum type; reading a bit pattern), and how it exposes byte order.
0.2 Prerequisites and scope
- Lecture 5: the stack frame (what lies above a local array: saved registers and the return address) and array address arithmetic. Both are central here.
- Lecture 2: two’s complement, IEEE float fields and byte order, used by the union demo.
- In scope: CS:APP §3.9 (structures, unions, alignment), §3.10.1 (process memory layout), §3.10.3–3.10.4 (buffer overflow and the three defenses, at concept level), and a one-paragraph note on §3.11 (floating-point code). The
attacklabtechniques themselves (code injection, return-oriented programming) are described in prose only.
0.3 Section → code map
| Section | Idea | Demo in code/lecture06/ |
|---|---|---|
| §1 | structures: layout and field access | 02_struct_code.py |
| §2 | alignment and padding; reordering fields | 01_struct_layout.c |
| §3 | arrays of structures | 01_struct_layout.c, 02_struct_code.py |
| §4 | the memory layout of a process; ASLR | 03_memory_layout.c |
| §5 | buffer overflow: the concept (no attack) | — |
| §6 | defense 1: code that cannot overflow | 04_bounded_strings.c |
| §7 | defenses 2–4: canary, NX, ASLR | 05_stack_protection.py |
| §8 | unions; byte order | 06_unions.c |
1. Structures
1.1 A struct is a block of memory
A structure groups values of possibly different types into one object. The slides’ running example:
struct rec {
int a[4]; // offset 0, 16 bytes
size_t i; // offset 16
struct rec *next; // offset 24
}; // size 32
The compiler lays the fields out in declaration order in one block of memory, choosing each field’s offset and the total size. In the assembly there are no field names, only offsets. r->i is 16(%rdi); r->next is 24(%rdi). Those offsets were fixed at compile time from the declaration. (This is why a binary file format or a network packet is really a struct layout, and why two programs that disagree about a struct’s declaration cannot exchange its data — a theme of Lecture 7.)
1.2 Field and array-element pointers
02_struct_code.py PART A takes the address of an array element inside a struct:
int *get_ap(struct rec *r, size_t idx) { return &r->a[idx]; }
leaq (%rdi,%rsi,4), %rax # r + 0 + 4*idx
a is at offset 0, so &r->a[idx] is just r + 4*idx: one lea, no memory access. A field at a non-zero offset would add that constant. The slides’ “Generating Pointer to Structure Member” is exactly this.
1.3 Following a linked list
long length(struct rec *r) {
long len = 0;
while (r) { len++; r = r->next; }
return len;
}
PART B traces it on a four-node list. The loop body is one pointer load from offset 24:
movq 24(%rdi), %rdi : r = M[0x10000 + 24] = 0x10200
movq 24(%rdi), %rdi : r = M[0x10200 + 24] = 0x10100
movq 24(%rdi), %rdi : r = M[0x10100 + 24] = 0x10300
movq 24(%rdi), %rdi : r = M[0x10300 + 24] = 0x0
The loop stops when it loads 0 (the last node’s next). This is the slides’ “Following Linked List”, and it is how every traversal of a tree, list or graph looks at the machine level: load a pointer field, test it, repeat.
2. Alignment
2.1 The rule, and why it exists
An object of a primitive type that needs B bytes must be stored at an address that is a multiple of B:
| Type | Size (bytes) | Address must be a multiple of |
|---|---|---|
char | 1 | 1 (any address) |
short | 2 | 2 |
int, float | 4 | 4 |
long, double, any pointer | 8 | 8 |
01_struct_layout.c PART A confirms these with _Alignof on the author’s machine; they are the same on arm64 and x86-64 (both LP64 with natural alignment).
Why align? Memory is physically accessed in aligned chunks of 4 or 8 bytes, and the caches in 64-byte blocks (Lecture 10), the virtual memory in 4 KiB pages (Lecture 11). A value that stays within its natural alignment never straddles two chunks, two cache lines or two pages, so it is fetched in a single access. x86-64 tolerates misaligned accesses (slowly); some architectures trap on them. Making alignment an ABI rule lets every compiler agree on a layout, which is what allows separately compiled code to share a struct.
2.2 Padding inside a struct
To keep each field aligned, the compiler inserts padding (unused bytes) before fields as needed. The slides’ struct S1 (demo 01 PART B):
struct S1 { char c; int i[2]; double v; }
field size align offsetof rules say padding before
c 1 1 0 0 0
i 8 4 4 4 3 <- 3 bytes of padding after c
v 8 8 16 16 4 <- 4 bytes of padding after i
sizeof = 24
c ends at offset 1, but int i[2] needs a multiple of 4, so 3 bytes are skipped to offset 4. i ends at 12, but double v needs a multiple of 8, so 4 more bytes are skipped to 16.
2.3 The alignment of a whole struct, and end padding
A struct has its own alignment K = the largest alignment of any of its fields, and its size is rounded up to a multiple of K. The slides’ struct S2:
struct S2 { long v; int i[2]; char c; }
v at 0, i at 8, c at 16
sizeof = 24 (7 bytes of padding at the end), alignment K = 8
Here all fields pack tightly (0, 8, 16), but c ends at offset 17, and K = 8 forces the size up to 24. Those 7 end-padding bytes exist for arrays (next section). Note K = 8 < sizeof = 24: a struct’s alignment is not its size.
The same two rules predict the compiler’s choice for every struct in the demo — all six, on both architectures:
6 of 6 structs: the rules predict the compiler exactly.
2.4 Reordering fields to save space
Fields stay in declaration order (C requires it), so padding is the price of a bad order. Compare S4 and S5, which hold the same fields:
struct S4 { char c; int i; char d; } -> sizeof 12 (c, pad×3, i, d, pad×2)
struct S5 { int i; char c; char d; } -> sizeof 8 (i, c, d, pad×2)
Putting the larger-alignment field first lets the small ones share the leftover bytes. Demo 01 computes the size after sorting each struct’s fields by decreasing alignment; for S4 that is 8, a third smaller. The compiler is not allowed to reorder fields for you (the standard fixes their order, and programmers rely on it for memory-mapped hardware and file formats), so this is the programmer’s job when memory matters.
3. Arrays of structures
An array of structs is a contiguous block; element idx starts at array + idx * sizeof(struct), where the size includes the end padding. That is what the end padding is for: it keeps every element — and therefore every field of every element — aligned. Demo 01 PART C, for struct S2 a[3] (24 bytes each):
&a[0] = a + 0 &a[0].c = a + 16
&a[1] = a + 24 &a[1].c = a + 40
&a[2] = a + 48 &a[2].c = a + 64
The machine code folds the struct size and the field offset into one address computation. The slides’ struct S3 { short i; float v; short j; } is 12 bytes, and a[idx].j is at a + 12*idx + 8 (02_struct_code.py PART C):
movslq %edi, %rcx
leaq (%rcx,%rcx,2), %rax # 3*idx
leaq _s3_array(%rip), %rdx
movswl 8(%rdx,%rax,4), %eax # M[s3_array + 4*(3*idx) + 8] = a[idx].j
3*idx scaled by 4 is 12*idx, the struct stride; +8 reaches field j. The cross-check (PART D) runs get_ap, length, get_j and set_val with valid indices on 65 inputs at -Og and -O1: 0 disagreements with the real x86-64 code and the native arm64 build.
4. The memory layout of a running program
4.1 The regions
A running x86-64 Linux process has its virtual address space divided into regions. From high addresses to low:
- Stack (top, around
0x7fff…on Linux): local variables and frames (Lecture 5). Grows down. Default limit 8 MiB. - Shared libraries (middle):
libcand others, mapped in. - Heap:
malloc/calloc/newmemory, grows up from just above the data. - Data: global and static variables and string constants.
- Text (bottom, around
0x400000): the program’s machine code, read-only.
4.2 Where things actually land, and ASLR
The slides’ “Memory Allocation Example” declares globals of 16 MiB and 2 GiB, mallocs blocks from 256 B to 4 GiB, and prints every address. 03_memory_layout.c does the same and runs itself three times to show what changes. On the author’s Mac:
object run 1 run 2 run 3 region bits that changed
phuge3 0x7300400000 0x7d48400000 0x7cca400000 huge malloc block 25..35
printf() 0x19315ad6c 0x19315ad6c 0x19315ad6c shared library (libc) none
local 0x16b771fbc 0x16fd8dfac 0x16f6b9fac stack 4..26
psmall2 0x145f59080 0x1418b5080 0x141f55080 small malloc block (heap) 14..26
big_array 0x104694004 0x100078004 0x10074c004 data (globals) 14..26
main() 0x10468ca68 0x100070a68 0x100744a68 text (code) 14..26
Three lessons, each measured:
- The pieces are where §4.1 says, with one twist the demo calls out: unlike the slides’ Linux picture, macOS puts the main thread’s stack below the malloc regions. The OS chooses the layout; C and the hardware do not care. (The demo prints the description that matches whichever OS it runs on.)
- Nothing is at a fixed address. Code, globals, heap and stack move from run to run. This is address-space layout randomization (ASLR), a security feature (§7). The code and globals move as one block — the distances inside it never change — in steps of whole pages: the low 12 bits (the offset within a 4 KiB page) are identical across runs.
- macOS randomizes shared libraries once per boot, not per run.
printf’s address was identical in all three runs here; on Linux it would move every run. The demo reports what it observed rather than assuming.
A fourth point from the huge allocations: the 2 GiB array and the 4 GiB malloc cost almost nothing until touched. Virtual memory only reserves addresses; physical pages are supplied on demand (Lectures 11–12).
5. Buffer overflow: the concept
5.1 What it is
C performs no bounds checking on array accesses (Lecture 5). Writing past the end of an array therefore overwrites whatever happens to lie beyond it in memory. When the array is a local variable on the stack, “beyond it” means — as you saw in Lecture 5 — the function’s saved registers and its return address. Overwriting the return address means that when the function executes ret, it jumps to an address controlled by the data that was written, not by the program. This bug class is called a buffer overflow (or, on the stack, stack smashing).
The slides recall Lecture 1’s memory-referencing bug (struct { int a[2]; double d; } with an out-of-range a[i] corrupting d) and generalize it. Historically this was for many years the number-one technical cause of security vulnerabilities, almost always through unchecked lengths on string input into a fixed stack buffer.
5.2 Where it comes from
The classic source is a library function that writes a string with no idea how big the destination is:
gets(buf)reads a line with no length limit at all. It is so dangerous that C11 removed it from the language.strcpy,strcatcopy a string of any length intobuf.sprintfformats intobufwith no size limit.scanf/sscanfwith a plain%sread a whitespace-delimited word of any length.
A C string carries no length, so a function that is not told the destination size cannot avoid overflowing it. That observation points straight at the first defense.
Scope. These notes stop at the concept. They do not show how to craft an input that overwrites a return address, nor how to inject or chain code. That material is the subject of
attacklab, which enrolled students do under the academic-integrity policy; reproducing a working attack here would serve no one. The rest of the lecture is about defending.
6. Defense 1 — write code that cannot overflow
The real fix is in your own code: use the functions that are told the destination size, and check their results. 04_bounded_strings.c runs each one against an 8-byte buffer ('.' = NUL, '_' = untouched, '~' = newline):
fgets(buf, n, stream) reads at most n-1 characters plus a NUL, and keeps the newline if the whole line fit:
input of 2 chars + newline: [hi~.____]
input of 7 chars + newline: [1234567.] <- no '~': line was too long
input of 12 chars + newline: [1234567.] <- 5 chars left unread
The presence or absence of the newline is how you detect truncation and decide what to do (here, drain the rest of the line and report an error).
snprintf(buf, n, ...) never writes more than n bytes (always NUL-terminated) and returns the length it wanted, so return value >= n means it truncated:
name "al" -> returned 7: [user=al.]
name "bob" -> returned 8: [user=bo.] <- returned 8 >= 8: truncated
strncpy(buf, src, n) is bounded but a trap: if src is exactly n bytes it copies all n and writes no terminating NUL, leaving an invalid string:
src "abcdefgh" (8 chars): [abcdefgh] <- no NUL anywhere!
So after strncpy you must set buf[n-1] = '\0' yourself, or prefer snprintf (or strlcpy where available). scanf("%7s", buf) caps the field at 7 characters.
The rule: never call a string-writing function without the destination’s size, and never pass input you do not control to gets/strcpy/strcat/sprintf. A modern compiler helps — -Wall warns about gets, and -D_FORTIFY_SOURCE=2 adds run-time length checks to these functions.
7. Defenses 2–4 — the system’s protections
Even with careful code, bugs slip through, so compilers and operating systems add three layers that make an overflow hard to exploit. 05_stack_protection.py shows them without ever performing an overflow.
7.1 Stack canaries
A canary is a secret value the compiler places on the stack between a function’s local buffer and its saved registers / return address. Just before returning, the function checks that the canary is unchanged. An overflow large enough to reach the return address must pass through the canary first and corrupt it, so the check fails and the program aborts in a controlled way (__stack_chk_fail) instead of returning to a corrupted address. It turns a silent, exploitable overwrite into an immediate, safe crash.
The demo compiles a benign function with -fstack-protector-all and reads the generated code. The added instructions (the slides’ “Setting Up Canary” and “Checking Canary”):
... load the secret guard (Linux: %fs:0x28; macOS: ___stack_chk_guard)
... store it just above the local buffer
... (the function body)
... load the stored value, compare it with the guard
... if equal, return; if not, call __stack_chk_fail (abort)
Running the protected function on a normal, in-bounds call in the simulator confirms the check is reached and passes (it never calls __stack_chk_fail), because nothing disturbed the canary. GCC and clang enable -fstack-protector-strong by default now.
7.2 Non-executable stack (NX / W^X)
Old x86 CPUs would execute instructions from any readable address, including the stack. x86-64 added a way to mark memory as not executable, and current systems mark the stack that way (“W^X”: a page is writable or executable, never both). Then even if an overflow writes bytes into a stack buffer, the CPU faults the instant it tries to execute them. This blocks the oldest form of attack, where the injected bytes were the attacker’s code. (It is why modern techniques reuse existing code instead — “return-oriented programming” — which is in turn why canaries and ASLR still matter. These notes name the technique but do not build one.)
7.3 Address-space layout randomization (ASLR)
Demo 03 already showed it: the stack, heap, code and libraries sit at random addresses that change every run. An attack that needs to jump to a specific address — of injected code, of a library function, of a chosen instruction sequence — cannot know that address in advance. ASLR does not fix the bug; it removes the attacker’s knowledge of where things are.
7.4 Why three
defense what it removes
stack canary a silent overwrite of the return address going undetected
non-executable stack (NX) running injected bytes as code
address randomization knowing where anything is
None is sufficient alone, and each targets a different assumption an attack would rely on. Together they turn what used to be a routine exploit into a hard one. The course teaches them so that you can both write safe code and understand the machinery that protects imperfect code.
8. Unions
8.1 One block, several views
A union allocates enough memory for its largest field, and all fields start at offset 0 — they share the storage. Only one is meaningful at a time. 06_unions.c PART A:
union U1 { char c; int i[2]; long v; } sizeof = 8; offsets c 0, i 0, v 0 (overlap)
struct with the same fields sizeof = 24; offsets c 0, i 4, v 16 (distinct)
A union is a space-saving tool when you know that only one of several interpretations is live at any moment.
8.2 Reading a bit pattern
Because the fields overlap, writing one and reading another reinterprets the same bytes. The slides’ example reads a float’s bits:
typedef union { float f; unsigned u; } bit_float_t;
float bit2float(unsigned u) { bit_float_t a; a.u = u; return a.f; }
unsigned float2bit(float f) { bit_float_t a; a.f = f; return a.u; }
PART B round-trips several floats and checks the bits against Lecture 2’s field formula:
value float2bit rebuilt round-trip
1.0 0x3f800000 1 ok
-2.0 0xc0000000 -2 ok
15213.0 0x46 eda800 15213 ok
This is not (unsigned)f: a cast converts the number (1.0 → 1), while the union reinterprets the bytes (1.0 → 0x3f800000). The union is the standard way to inspect or assemble a floating-point value’s bits.
8.3 Byte order, made visible
A union over the same bytes seen as different widths exposes endianness. The slides’ dw example writes bytes f0 f1 … f7 and reads them back as shorts, ints and a long (PART C):
chars c[0..7] = f0 f1 f2 f3 f4 f5 f6 f7 (low address first)
shorts s[0..3] = f1f0 f3f2 f5f4 f7f6
ints i[0..1] = f3f2f1f0 f7f6f5f4
long l[0] = f7f6f5f4f3f2f1f0
On little-endian x86-64 (and arm64), the first byte written, f0, is the least significant of each wider value, so s[0] reads f1f0 and l[0] reads f7f6f5f4f3f2f1f0. A big-endian machine would show s[0] = f0f1 and l[0] = f0f1…f7. This is why binary data exchanged between machines (files, network packets) needs an agreed byte order — the Internet’s is big-endian (Lecture 19).
8.4 Using a union safely
The language does not record which field of a union is live, so reading the “wrong” field silently reinterprets bytes (§8.2) — useful on purpose, a bug by accident. The safe pattern is a tagged union (“sum type”): a struct holding the union plus a separate tag saying which field is valid (PART D):
typedef union { long i; double d; } num_t;
typedef struct { bool is_double; num_t val; } value_t;
Read val.d only when is_double is true. The tag is what makes the union safe.
9. A note on floating-point code (CS:APP §3.11)
The slides mention, and CS:APP §3.11 covers, that floating-point arguments travel in the %xmm0–%xmm7 registers, a float/double result comes back in %xmm0, and arithmetic uses the SSE instructions (addss, mulsd, cvtsi2sd, …) on those registers rather than the general-purpose ones. The 2026 course treats this briefly; these notes follow suit. The union trick of §8.2 is the usual way to see a float’s bits, independent of the floating-point unit.
Summary
- A struct is a block of memory; a field is a fixed offset the compiler computes from the declaration. The assembly has offsets, not names (
r->next=24(%rdi)). - Alignment: a field of size/alignment
Ksits at a multiple ofK; the struct’s alignment is its largest field’s, and its size is rounded up to that, adding internal and end padding. Reordering fields (largest alignment first) minimizes padding; the compiler may not do it for you. - An array of structs strides by the full struct size, padding included, which is exactly what keeps every element aligned.
- A process’s memory is stack (high) / libraries / heap / data / text (low). ASLR moves these to random addresses every run (per boot for macOS libraries), measured in demo 03.
- A buffer overflow writes past a stack array into the saved registers and return address, because C does not check bounds; it was the leading security-bug class. (Concept only here; no attack is built.)
- Four defenses: write code that cannot overflow (bounded functions, checked for truncation), stack canaries (detect an overwrite), non-executable stack (injected bytes cannot run), ASLR (addresses are unknown). Complementary, none sufficient alone.
- A union holds one of its fields at a time, all at offset 0. It reinterprets bytes (reading a float’s bits; exposing endianness) and is safe only with a tag saying which field is live.
Common pitfalls
- Assuming no padding.
sizeof(struct)is usually more than the sum of the field sizes. Never compute a struct’s size by adding its fields; asksizeof. - Writing a struct to a file and reading it on another machine. Padding and byte order differ between compilers and architectures; serialize field by field with an agreed layout instead.
strncpyleaving no terminator. For a source as long as the buffer, there is no NUL; terminate it yourself or usesnprintf.- Trusting input length. Any
gets/strcpy/sprintf/scanf("%s")on data you do not control is a latent overflow. Use the bounded forms and check for truncation. - Thinking a canary or ASLR fixes the bug. They make exploitation harder; the overflow is still a bug, and still undefined behavior that can crash or corrupt.
- Reading the wrong union field. Without a tag, the value is just a reinterpretation of whatever was last written.
Exercises
-
Lay it out. Give the offset of every field and the
sizeofforstruct { char a; double b; int c; char d; };.Answer
a at 0; 7 bytes padding; b at 8; c at 16; d at 20; 3 bytes end padding. K = 8, sizeof = 24. Reordered `{ double b; int c; char a; char d; }`: 0, 8, 12, 13, then 2 padding → 16 bytes. -
Why end padding?
struct S2ends with 7 unused bytes. Remove them (imaginesizeofwere 17). What breaks forS2 a[2]?Answer
`a[1]` would start at offset 17, so `a[1].v` (a `long`, alignment 8) would be at a non-multiple of 8. The end padding rounds the size to 24 so every element — and every field of every element — stays aligned. -
Read the access.
struct P { int x; int y; char tag; };andshort f(struct P *p, long k) { return p[k].tag; }. What is the address ofp[k].tagin terms ofpandk, and what issizeof(struct P)?Answer
sizeof = 12 (x at 0, y at 4, tag at 8, 3 end padding). `p[k].tag` is at `p + 12*k + 8`. -
Shrink it. Reorder
struct { char c; double d; int i; short s; char b; };to use the least space. Give both sizes.Answer
Original: c@0, pad7, d@8, i@16, s@20, b@22, pad1 → 24. Sorted `{ double d; int i; short s; char c; char b; }`: 0, 8, 12, 14, 15, pad0 → 16. 24 vs 16. -
What overwrites what? In a frame with
char buf[8]just below the saved%rbxand the return address, which bytes of an over-long write reach the return address first — and which defense notices? (Concept, not a construction.)Answer
Writing past `buf` goes toward higher addresses: first any padding/canary, then saved registers, then the return address. A **stack canary** sits between `buf` and the saved registers, so it is corrupted before the return address is, and the exit check catches it. -
Which call is safe? (a)
gets(buf)(b)fgets(buf, sizeof buf, stdin)(c)sprintf(buf, "%s", s)(d)snprintf(buf, sizeof buf, "%s", s)(e)strcpy(buf, s). Which cannot overflowbuf, and which of the safe ones can still silently truncate?Answer
Safe from overflow: (b) and (d). Both can truncate — detect it with `fgets` (no `'\n'`) and `snprintf` (return value ≥ size). (a), (c), (e) can all overflow for long input. -
Cast vs union. For
float f = 1.0;, what is(unsigned)f, and what doesfloat2bit(f)(the union) return? Why different?Answer
`(unsigned)f` = 1 (a numeric conversion). `float2bit(f)` = `0x3f800000` (the IEEE bit pattern of 1.0). The cast converts the value; the union reinterprets the bytes. -
Endianness. A union writes bytes
01 02 03 04intounsigned char c[4]. What isunsigned int i(the overlapping field) on little-endian x86-64, and on a big-endian machine?Answer
Little-endian: `0x04030201`. Big-endian: `0x01020304`. The first byte written is least significant on little-endian, most significant on big-endian.
The related lab: L3 (attacklab)
attacklab teaches you to recognize and reason about stack overflows by exploiting a provided target program under controlled, authorized conditions in the course. These notes support the understanding it rests on — the stack frame (Lecture 5), what lies above a local buffer, and the three defenses — but contain no attack construction and no lab solutions. The defensive habits here (bounded input functions, reading the canary code, knowing what NX and ASLR do) are the other half of the same knowledge: the lab shows why unsafe code is dangerous; this lecture shows how not to write it. Recitation covers the gdb workflow for the lab.
Further reading
- CS:APP3e §3.9 (structures, unions, alignment), §3.10.1 (memory layout), §3.10.3–3.10.4 (overflow and defenses), §3.11 (floating-point code); practice problems 3.44–3.49.
- The System V AMD64 ABI, §3.1 (aggregate and union layout rules).
man 3 fgets,man 3 snprintf,man 3 strncpy,man 3 strlcpy; the C11 rationale for removinggets.- GCC/clang flags:
-fstack-protector-strong,-D_FORTIFY_SOURCE=2,-Wl,-z,noexecstack,-fPIE -pie;readelf -l(Linux) orotool -l(macOS) to see segment permissions.
Preview of Lecture 7: Linking
You have seen that a struct’s field offsets, a global array’s address and a called function’s address are all fixed before the program runs. Who fixes them? Lecture 7 is about the linker, which combines separately compiled .o files into one program: it performs symbol resolution (matching each use of a name to its definition — and the dangerous rules for duplicate globals, which can silently corrupt data exactly as a struct mismatch would) and relocation (filling in the final addresses, including the %rip-relative references you saw in Lectures 5–6). It explains static vs shared libraries, why link order matters, and how LD_PRELOAD can interpose on malloc.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| structure (struct) | 结构体 |
| field / member | 字段 / 成员 |
| offset | 偏移量 |
| union | 联合体(共用体) |
| tagged union / sum type | 带标记联合 / 和类型 |
| alignment | 对齐 |
| padding (internal / external) | 填充(内部 / 外部) |
| natural alignment | 自然对齐 |
| alignment requirement K | 对齐要求 K |
| array of structures | 结构体数组 |
| stride | 步长 |
| row-major / contiguous | 行优先 / 连续存放 |
| memory layout | 内存布局 |
| text / data / heap / stack segment | 代码段 / 数据段 / 堆 / 栈 |
| shared library | 共享库(动态库) |
| virtual address space | 虚拟地址空间 |
| address-space layout randomization (ASLR) | 地址空间布局随机化 |
| buffer overflow / stack smashing | 缓冲区溢出 / 栈溢出攻击 |
| return address | 返回地址 |
| bounds checking | 边界检查 |
| truncation | 截断 |
| stack canary | 栈金丝雀(栈保护值) |
| guard value | 保护值 |
__stack_chk_fail | 栈检查失败处理函数 |
| non-executable stack (NX / W^X) | 不可执行栈 |
| code injection | 代码注入 |
| return-oriented programming (ROP) | 面向返回编程 |
| thread-local storage (%fs) | 线程本地存储 |
| defense in depth | 纵深防御 |
| endianness (little / big) | 字节序(小端 / 大端) |
| reinterpret (bits) | 重新解释(位模式) |
| IEEE 754 fields (sign / exponent / fraction) | IEEE 754 字段(符号 / 阶码 / 尾数) |
%xmm registers / SSE | 向量寄存器 / SSE 指令 |