What is data alignment and why does it matter?
Alignment means storing a K-byte value at an address divisible by K — e.g. a 4-byte int at an address that's a multiple of 4.
* A K-byte type belongs at an address divisible by K, so the CPU reads it in one fetch instead of two. *
The rule is simple: a primitive type that needs K bytes should sit at a K-byte-aligned address. So a char can go anywhere, a short at even addresses, an int at multiples of 4, and an 8-byte long or pointer at multiples of 8.
| Type | Size | Required alignment |
|---|---|---|
| char | 1 | 1 (any address) |
| short | 2 | 2 |
| int | 4 | 4 |
| long / pointer | 8 | 8 |
Why bother? Memory hardware fetches in aligned chunks (4 or 8 bytes). A value that straddles a chunk boundary forces two memory accesses instead of one, and can even span two virtual-memory pages, which complicates the OS. On some architectures a misaligned access is an outright CPU fault; x86 tolerates it but pays the performance penalty. Aligned accesses are also atomic on x86, and many SIMD vector instructions require 16- or 32-byte alignment.
Note: the slides phrase the base rule as "required on some machines; advised on IA32" — x86 forgives misalignment, but you still want to avoid it.
Go deeper:
Data structure alignment (Wikipedia) — the definitive article on alignment and its performance cost.