Lesson 96 +10 XP

Struct Padding and Memory Layout

Struct Padding and Memory Layout

A struct's size isn't always the sum of its fields. The compiler may add padding to align data.

The surprising size

struct Example {
    char a;      // 1 byte
    int b;       // 4 bytes
};
printf("%d", sizeof(struct Example));

You might expect 5, but you often get 8 - the char is padded to keep the int aligned.

Why padding?

CPUs like aligned data. The compiler inserts unused bytes so each member starts at a "nice" address.

Order matters

Group same-size members together to reduce padding:

struct Packed {
    int b;        // 4
    char a;       // 1, then padding to the end
};

Use sizeof, don't guess

The layout can vary by compiler and platform. Always ask with sizeof.

TL;DR

  • Padding = extra bytes inserted for alignment.
  • A struct's size can exceed the sum of its fields.
  • Reordering fields can shrink padding.
  • Use sizeof, don't hard-code sizes.