CPU word size and alignment
What you'll learn: Why the CPU reads memory in "chunks" called words and how this affects how your variables are stored.
The CPU's "Large Hands"
We often imagine memory as a long string of individual bytes, and we think the CPU can reach out and grab any single byte it wants. In reality, the CPU has "large hands." It doesn't pick up one byte at a time; it grabs memory in fixed-size blocks called words.
On a 64-bit system, a word is 8 bytes. On a 32-bit system, it is 4 bytes. Think of the CPU as a construction worker who can only lift boxes that are exactly 4 feet wide. If he needs something inside a box, he has to pick up the whole box, bring it to his workbench, and then look inside.
Why Alignment Matters
The CPU is most efficient when data starts at an address that matches a multiple of its word size. This is called alignment.
If you have a 4-byte integer, the CPU prefers it to start at an address like 0, 4, 8, or 12. If the integer is "aligned," the CPU can grab it in one single "reach."
However, if you force an integer to start at an awkward spot—say, address 3—the integer will straddle the boundary between two different words. To read that one integer, the CPU now has to perform two memory reads, shift the bits around, and glue them together. This slows your program down.
Padding: The Space Between
To keep things fast, the C compiler automatically adds invisible "empty space" between variables to ensure they land on the correct boundaries. This is called padding.
#include <stdio.h>
struct Data {
char a; // 1 byte
// 3 bytes of invisible padding added here!
int b; // 4 bytes
};
int main() {
// You might expect this to be 5 bytes, but it will likely be 8.
printf("Size of struct: %zu bytes\n", sizeof(struct Data));
return 0;
}
In the example above, the compiler sees that int b needs to start on a 4-byte boundary. It leaves a 3-byte gap after char a so that b stays aligned. Without this padding, the CPU would have to work twice as hard to read the value of b.
Key takeaway
Alignment ensures the CPU can grab data in a single cycle by placing variables at addresses that match the CPU's word-sized "grip."