liveBook · Manning

Padding

As explained in Modern C, Third Edition

Byte padding is unused whole-byte storage inserted within or after a structure to satisfy layout or alignment requirements.

A compiler may insert one or more unused whole bytes after a structure member so the next member begins at a suitable alignment boundary. Padding can follow any member, but never begins a structure. section 6.3.4

Keep these layout rules in mind:

  • Member order remains the declared order, even when alignment introduces wasted space. section 6.3.4
  • Reordering members can reduce wasted padding bytes, although the resulting layout still depends on compiler alignment choices. section 6.3.4
  • Do not confuse byte padding with bit padding: bit padding can waste individual bits, including inside unsigned values. section 6.3.4
// *** This has errors, don't use it! ***
struct tib {
  int tib_sec  :6; // Seconds after the minute    [0, 60]
  int tib_min  :6; // Minutes after the hour      [0, 59]
  int tib_hour :5; // Hours since midnight        [0, 23]
  int tib_mday :5; // Day of the month            [1, 31]
  int tib_mon  :4; // Months since January        [0, 11]
  int tib_year;    // Years since 1900
  int tib_wday :3; // Days since Sunday           [0, 6]
  int tib_yday :9; // Days since January          [0, 365]
  int tib_isdst:1; // Daylight Saving Time flag
};

Use this bit-field listing as a contrast with byte padding; its comments show compact bit allocation, and the listing is explicitly marked as erroneous. section 6.3.4

How Modern C, Third Edition covers it

How deep it goes
Defines placement rules and reduction by member ordering, while deferring alignment details to a later treatment.
Examples
Uses a person structure layout and contrasts byte padding with compact time-related bit-field declarations.
What it assumes
Assumes structures, members, and compiler-selected storage layout.
What you can do after
Evaluate structure layouts and reduce potential waste by considering member order.
How it connects
Connects structure members with alignment, member ordering, bit padding, and bit-fields.

Also explained in

Compare how 19 books explain padding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.