Address alignment describes the process by which addresses are allocated such that they are multiples of the object's size. Aligned addresses are faster to access on most CPU's and on some unaligned addresses are not supported.
Structures are aligned differently to basic data types as they are composites, their alignment follows the following 3 rules:
When padding is introduced it must always be added between or after fields, ensuring that the alignment of the field before the padding is maintained.
Given the following struct determine the offset of b as well as the total size of the struct and the alignment
struct ExampleOne {
char a;
int b;
short c;
};
The individual fields have sizes of 1, 4, and 2 bytes respectively meaning the overall alignment of the struct must be 4 bytes, the size of the fields in the struct total to 7 bytes, meaning it must be padded up to 12 bytes, we can do this by adding padding of 3 bytes to a and 4 bytes to the end of c.
| Field | Size (Bytes) | Offset |
|---|---|---|
char a; |
1 | 0 |
| padding | 3 | |
int b; |
4 | 4 |
short c; |
2 | 6 |
| padding | 4 | |
| Total: 12 |