Learn C Programming

Lesson 6 of 9 · Structures, Unions and Enums

Module 12 · Structures, Unions and Enums

Under the Hood: Padding, Alignment and sizeof Surprises

ProReading

Kenji wants to keep a million sensor records in memory. Each record is a char, an int and another char. He adds up the fields: 1 + 4 + 1 is 6 bytes, so a million records need 6,000,000 bytes. Then he asks the Playground for sizeof, and it prints 12.

Checking what this lesson needs for you…

What is inside Under the Hood: Padding, Alignment and sizeof Surprises

  1. sizeof surprises: six bytes of fields, twelve bytes of struct
  2. offsetof: where each field starts
  3. The rule: every field starts at a multiple of its alignment
  4. The padding at the end keeps an array aligned
  5. Reordering fields to shrink a struct
  6. Why alignment exists
  7. Padding bytes hold anything, so compare field by field
  8. packed: no padding, and not portable