Chapter 16: C and the Memory Model
Vol 3: Computer Core Expedition · Chapter 16
Metadata Card
| Attribute | Value |
|---|---|
| Keywords | Pointers, Stack vs Heap, Buffer Overflow, Undefined Behavior, Memory Safety |
Your Progress
"C gives you unparalleled control over memory — and unparalleled ability to shoot yourself in the foot."
Encounter 1: Stack vs Heap
| Stack | Heap | |
|---|---|---|
| Allocation | Automatic (function calls) | Manual (malloc, free) |
| Size | Small (MB) | Large (GB) |
| Lifetime | Function scope | Until freed |
| Speed | Very fast | Slower |
| Fragmentation | None | External fragmentation |
Encounter 2: Pointers and Arrays
c
int arr[10]; // arr is a pointer to the first element
int *p = arr; // p points to arr[0]
*(p + 3) = 42; // same as arr[3] = 42Encounter 3: Buffer Overflow
Writing beyond the bounds of an array or buffer. Classic vulnerability:
c
void vulnerable(char *input) {
char buf[64];
strcpy(buf, input); // No bounds check!
}If input is longer than 63 characters, it overwrites the return address on the stack — enabling code injection attacks.
Encounter 4: Undefined Behavior (UB)
In C, certain operations have UNDEFINED behavior:
- Signed integer overflow
- Use-after-free
- Buffer overflow
- Dereferencing NULL
- Data race
The compiler may assume UB never happens and generate unexpected code.
Verification Checklist
- [ ] Can explain stack vs heap allocation
- [ ] Can identify a buffer overflow vulnerability
- [ ] Can list common C undefined behaviors
- [ ] Can explain what happens during a function call (stack frame)
→ Next Stop Preview
Chapter 17: Assembly Basics and Calling Conventions