Why the compiler adds padding bytes
What you'll learn: How your computer’s hardware efficiency forces the compiler to insert "invisible" empty space between variables in a structure.
The hardware "Bus" analogy
Imagine a library where the librarian only moves books using a large cart that fits exactly four books at a time. If you ask for a specific book, the librarian doesn’t just grab that one; they push the cart to the shelf and bring back a full block of four.
Your computer's CPU works similarly. It reads data from RAM in fixed chunks (often 4 or 8 bytes) called "words." If a piece of data starts exactly at the beginning of one of these chunks, the CPU can grab it in one quick trip. If the data is split across two chunks, the CPU has to make two trips, shift the pieces around, and glue them together. This slows your program down.
Enter: Padding
To keep things fast, the C compiler performs "Data Alignment." It ensures that variables start at memory addresses that are easy for the CPU to read. If a small variable (like a 1-byte char) is followed by a larger one (like a 4-byte int), the compiler won't squeeze them together. Instead, it leaves "padding" bytes—empty, wasted space—to make sure the int starts on a clean 4-byte boundary.
Seeing the invisible
Take a look at this structure. You might expect it to take up 5 bytes (1 + 4), but the compiler has other plans:
struct SecretPadding {
char a; // 1 byte
// The compiler inserts 3 hidden padding bytes here!
int b; // 4 bytes
};
// sizeof(struct SecretPadding) will likely return 8, not 5.
In this example, the compiler sees that b needs to be aligned. Rather than letting b start at byte 1 (which is "misaligned"), it adds three invisible bytes after a so that b starts at byte 4.
Why this matters
Padding isn't a bug; it’s a performance feature. While it "wastes" a few bytes of RAM, it saves your CPU from doing extra work every time it accesses your data. However, as a programmer, you should be aware that the order in which you define your variables can change how much padding is added, potentially making your structures larger than they need to be.
Key takeaway
The compiler adds padding bytes to align data with the CPU’s natural "word" boundaries, sacrificing a little memory to ensure your program runs at maximum speed.