Understanding memory alignment
What you'll learn: Why the CPU requires data to be arranged at specific memory addresses and how this creates "gaps" in your structures.
The Post Office analogy
Imagine a post office where the mail sorter can only pick up four envelopes at a exact time, but only if they are perfectly aligned in a stack. If you place one envelope slightly off-center, the sorter has to stop, adjust its grip, and take two trips to pick up what should have been one load.
Computers work similarly. Modern CPUs don't read memory one byte at a time; they read in "chunks" (typically 4 or 8 bytes). To keep performance high, the CPU expects a 4-byte integer to start at an address that is a multiple of 4. This requirement is called memory alignment.
Meet the "Padding"
When you create a struct, you might assume the members are packed tightly together. However, if the members have different alignment requirements, the compiler will insert invisible, empty bytes called padding to ensure every piece of data sits at a "natural" boundary.
Consider this structure:
struct Data {
char a; // 1 byte
// 3 bytes of hidden padding inserted here!
int b; // 4 bytes
char c; // 1 byte
// 3 bytes of hidden padding added at the end!
};
You might expect this struct to be 6 bytes (). However, if you run sizeof(struct Data), you will likely see 12 bytes.
The compiler sees that int b needs to start on a 4-byte boundary. Since a only takes 1 byte, the compiler leaves 3 bytes of "dead space" so that b starts at offset 4. Then, it adds padding at the end so that if you created an array of these structures, the next int b in the second element would also be correctly aligned.
Why should you care?
Padding isn't a bug; it's a trade-off. The compiler wastes a little bit of RAM to ensure the CPU can access your data at maximum speed. If you are working on systems with very limited memory, you can minimize this waste by ordering your struct members from largest to smallest, which allows the smaller variables to "fill in" the gaps naturally.
Key takeaway
Memory alignment ensures the CPU can read data efficiently by inserting invisible padding bytes between struct members to align them with hardware boundaries.