Home / Learn Embedded C / Struct Padding and Alignment
Struct Padding and Alignment
Why a struct can be bigger than the sum of its fields.
How to think about this
In plain terms
A CPU often requires (or strongly prefers) that multi-byte values sit at addresses that are a multiple of their size; the compiler inserts invisible "padding" bytes into a struct to satisfy this, which can make the struct larger than its fields alone.
Why we use it
Assuming a struct's size exactly matches the sum of its field sizes is a common and surprising embedded bug — especially when a struct is written out byte-by-byte to a file or sent over a protocol.
Under the hood
A char (1 byte) followed by an int (commonly 4-byte aligned) often gets 3 padding bytes inserted between them so the int starts at a 4-byte boundary; reordering fields from largest to smallest usually minimizes this waste.
Real-world use
- Protocol packing
- Binary file formats
- Register-map structs
Try it
This arithmetic mirrors what a real compiler works out automatically when laying out a struct with a char field followed by an int field.
#include <stdio.h>
struct Example {
char flag; /* 1 byte */
int value; /* 4 bytes, but padded to start at a 4-byte boundary */
};
int main() {
printf("sizeof(struct Example) = %zu\n", sizeof(struct Example));
/* On many 32-bit compilers this prints 8, not 5 (1 + 4), because of 3 padding bytes. */
return 0;
}Try it: reordering fields to avoid padding
Putting the largest field first and grouping small fields together is a common trick real firmware engineers use to shrink struct size.
Quick quiz
1. Why might sizeof(a struct) be larger than the sum of its fields' individual sizes?
Alignment requirements force the compiler to insert invisible padding between (or after) fields.