CC Explainer
C · 5 · Systems C24 / 35 · 69%

Alignment, Padding & Undefined Behavior

Structs are padded so each field lives on its natural boundary. Break the rules and the compiler is allowed to do anything.

shortcuts: ← prev · → next · M mark
1

Struct Padding

The compiler adds hidden bytes so int lands on a 4-byte boundary.

Example
example
struct Bad  { char c; int i; char c2; };    // 12 bytes
struct Good { int  i; char c; char c2; };   // 8 bytes

printf("%zu %zu\n", sizeof(struct Bad), sizeof(struct Good));
TIP
Order fields largest-to-smallest to shrink structs.
2

Undefined Behavior

The compiler assumes UB never happens — and optimises accordingly.

Example
example
int x = INT_MAX;
x + 1;             // signed overflow = UB

int a[3];
a[3] = 0;          // out-of-bounds = UB

int *p; *p = 1;    // uninitialised pointer = UB
WATCH OUT
Enable -fsanitize=undefined during development to catch these at runtime.
3

volatile & restrict

Two little qualifiers that change codegen.

Example
example
volatile int *reg = (int*)0x40000000; // hardware register — do not cache
*reg = 1;

void copy(int * restrict dst, int * restrict src, int n) {
    // compiler assumes dst and src don't overlap → can vectorise
    for (int i = 0; i < n; i++) dst[i] = src[i];
}