Home / Learn Embedded C / Struct Padding and Alignment

Struct Padding and Alignment

Why a struct can be bigger than the sum of its fields.

Quick summaryWhy a struct can be bigger than the sum of its fields.

How to think about this

A padded struct in memory: char, then int (not reordered)char field6356padding (unused)5532int field310
A padded struct in memory: char, then int (not reordered)

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

Computing how much padding a char-then-int layout needsC: edit and run

This arithmetic mirrors what a real compiler works out automatically when laying out a struct with a char field followed by an int field.

Careful:This course's sandbox cannot run struct code directly (see the C refresher group), so this lesson is theory-and-diagram only — but the effect is very real on actual hardware and shows up constantly in protocol/driver code.
A struct whose size is larger than its fields alone, due to padding (reference only — not runnable in this sandbox)
#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

Comparing worst-case vs best-case field orderingC: edit and run

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?