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:
Instead, with padding:
Offset: 0 1 2 3 4 5 6 7
A _ _ _ V V V V
^Padding^ ^--Value--^
The CPU can now:
Value
in a single operationThis 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.
Answers to questions are automatically generated and may not have been reviewed.
Learn how memory alignment affects data serialization and how to handle it safely