Sub topic 7
Alignment, padding, and field order
This chapter assumes you can read C structs and pointers, and that you know a cache line is the unit of transfer between memory and the CPU (about 64 bytes on common x86-64 and ARM parts, though not guaranteed).
Alignment and padding
Alignment means a value of size N is normally stored at an address that is a multiple of N. A double sits at a multiple of 8, an int at a multiple of 4. Misaligned access is slower on some CPUs, faults on others, and can straddle two cache lines.
To keep every field aligned, the compiler inserts unused bytes called padding. It also pads the end of the struct so that each element of an array stays aligned. The struct's own alignment equals that of its most strictly aligned field.
Field order changes size
C lays out fields in declaration order, so order decides how much padding appears.
#include <stdio.h>
/* Poor order: padding is inserted after 'a' and after 'c'. */
struct Wasteful {
char a;
double b;
char c;
};
/* Better order: largest alignment first. */
struct Compact {
double b;
char a;
char c;
};
int main(void) {
/* Typically prints 24 and 16 on x86-64 with common ABIs. */
printf("%zu %zu\n", sizeof(struct Wasteful), sizeof(struct Compact));
return 0;
}In Wasteful, a takes 1 byte, 7 bytes of padding follow so b lands on a multiple of 8, b takes 8, c takes 1, and 7 bytes of tail padding round the size up to 24. In Compact, b takes 8, a and c take 2, and 6 bytes of tail padding give 16.
Why this matters for caches
A 64-byte line holds two or three Wasteful elements, but exactly four Compact elements. Sixteen-byte elements also never straddle a line boundary when the array starts on a 64-byte boundary, while 24-byte elements sometimes do. Smaller structs mean fewer lines loaded for the same number of elements, so a scan over a large array moves about a third less data.
A rule of thumb is to sort fields from largest alignment to smallest. If fields are used together, keep them close, and prefer smaller types (such as uint8_t flags or uint32_t indices) when the range allows it.
Common errors
- Assuming
sizeofis the sum of the field sizes. It includes padding. - Reordering a struct that is part of a file format, network protocol, or shared ABI. The layout is part of the contract.
- Using
#pragma packor__attribute__((packed))to remove padding. Packing can cause misaligned loads, slower code, and undefined behavior when you take pointers to fields. - Forgetting that C++ and Rust may differ. Rust reorders fields by default unless you ask for
#[repr(C)].
Exercise
A struct declares char a; int b; char c; short d; in that order on a typical x86-64 ABI. What is its size, and what order of the same fields minimizes it?
Show answer
In the given order, a is at 0, 3 bytes of padding, b at 4, c at 8, 1 byte of padding, d at 10, for 12 bytes total (already a multiple of 4). Ordering int b; short d; char a; char c; gives 4 + 2 + 1 + 1 = 8 bytes with no padding.