Why Computer Memory Needs Padding
Why do we need padding at all? Can't the computer just read the bytes it needs?
Modern CPUs are designed to read memory most efficiently when data is properly aligned. While it's technically possible to read individual bytes from any address, doing so can severely impact performance and, on some architectures, even cause crashes.
Let's understand why through an example. Imagine we have a 32-bit integer stored at memory address 1:
#include <iostream>
struct Unaligned {
char A;// at offset 0
int Value;// at offset 1 (unaligned!)
};
int main() {
Unaligned Data;
Data.A = 'X';
Data.Value = 42;
std::cout << "Size with alignment: "
<< sizeof(Unaligned) << " bytes\n";
}
Size with alignment: 8 bytes
When the CPU needs to read Value
, it has to:
- Read bytes 1-4 (crossing a 4-byte boundary)
- Perform additional operations to combine these bytes
- Use more complex circuitry that handles unaligned access
Instead, with padding:
Offset: 0 1 2 3 4 5 6 7
A _ _ _ V V V V
^Padding^ ^--Value--^
The CPU can now:
- Read all 4 bytes of
Value
in a single operation - Use simpler circuitry optimized for aligned access
- Better utilize the cache line
This is why the compiler adds 3 bytes of padding after A
- the small space "wasted" by padding is far outweighed by the performance benefits of aligned access.
Padding and Alignment
Learn how memory alignment affects data serialization and how to handle it safely