Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 135 ยท Structures and Unions

Padding and Alignment

Learn why C structs have holes: alignment rules, padding, offsetof, alignof and alignas, reordering members, packed structs and aligned_alloc.

Add up the sizes of a struct's members and you'll often get a smaller number than sizeof reports. A struct with a char, an int and another char holds 6 bytes of data, yet on a typical 64-bit machine it occupies 12. The extra bytes are padding: unused gaps the compiler inserts so that every member sits at an address the processor can access efficiently, an address with the right alignment.

Padding is invisible most of the time, but it matters when you store millions of structs, write structs to files or the network, compare them with memcmp, or talk to hardware. This lesson explains the alignment rules, shows you how to see the holes with offsetof, how to remove most of them by reordering members, and how to control alignment with C11's alignof and alignas.

What alignment means

Every type has an alignment requirement: a power of two, and objects of that type must start at an address that is a multiple of it. On x86-64 Linux (the machine behind our editor), the alignment of each basic type equals its size: char 1, short 2, int 4, double 8, pointers 8. You can ask the compiler with alignof:

C Sizes and alignments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

alignof is a keyword in C23. In C11 and C17 the keyword is spelled _Alignof, and <stdalign.h> provides alignof as a macro, so #include <stdalign.h> makes this code work on older compilers too. max_align_t (from <stddef.h>) is a type with the largest alignment any basic type needs; malloc always returns memory aligned at least that well.

Why do processors care? Memory is read in aligned chunks. A 4-byte int that starts at a multiple of 4 is read in one access. A misaligned one might span two chunks, so some processors need two accesses and a merge, and some (older ARM, SPARC) simply fault. The C standard says that accessing an object through a misaligned pointer is undefined behavior, whatever the hardware does.

Where padding comes from

When the compiler lays out a struct, it places members in the order you declared them, and before each member it adds just enough padding to reach that member's alignment. The offsetof macro from <stddef.h> tells you where each member starts:

C Seeing the holes with offsetof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Here's the layout of struct badly_ordered, one character per byte (p = padding):

TEXT
offset:  0  1  2  3  4  5  6  7  8  9 10 11
         T  p  p  p  C  C  C  C  F  p  p  p
  • tag sits at 0.
  • count needs an address that is a multiple of 4, so 3 padding bytes follow tag and count starts at 4.
  • flag fits at 8.
  • Then come 3 more bytes of trailing padding, making the size 12.

struct sample is worse: 1 + 8 + 2 = 11 bytes of data in 24 bytes of struct, because value must start at 8 and the size must be a multiple of 8.

Why trailing padding exists

The trailing bytes look pointless until you make an array. Array elements sit right next to each other, so element i starts at i * sizeof(struct). For every element's count to stay aligned, the struct size must be a multiple of the struct's alignment, which is the largest alignment of any member. A 9-byte struct badly_ordered would put the second element's count at offset 13, misaligned. Rounding the size up to 12 fixes every element at once.

Two rules sum it up:

  1. Each member starts at a multiple of its own alignment.
  2. The struct's alignment is its strictest member's alignment, and its size is a multiple of that.

The standard guarantees only that the first member is at offset 0 and that members appear in declaration order. The exact padding is up to the platform's ABI, but nearly every mainstream compiler follows these two rules.

Reordering members to save space

The compiler may not reorder members for you, but you can. Sorting members from the largest alignment to the smallest removes nearly all internal padding:

C Same data, less padding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Both structs hold the same 8 + 8 + 4 + 1 + 1 + 1 = 23 bytes of data. The wasteful order needs 40 bytes per player; the compact order needs 24, the 23 data bytes plus one byte of trailing padding. For a million players that's 16 MB saved, and more players fit in each cache line, which often makes loops over the array faster too. (The 1'000'000 digit separator is C23.)

Reordering is a judgment call. Sometimes you group members by meaning, keep "hot" members that are used together at the front, or must keep an order that matches a published layout. Optimize the layout of structs you have many of; for a struct with a single instance, readability matters more.

Tip: GCC and Clang have a -Wpadded warning that reports every struct the compiler pads. It's too noisy to leave on, but it's handy for auditing a header once. Tools like pahole show the layout and holes of every struct in a compiled program.

Padding bytes have unspecified values

The bytes in the holes belong to no member. Assigning to members never writes them, so their contents are unspecified, possibly leftover data from earlier use of that memory. That has three consequences:

  • Don't compare structs with memcmp. Two structs with equal members can differ in their padding. Compare member by member instead. (C has no == for structs.)
  • Don't hash the raw bytes of a struct for the same reason.
  • Clear structs before writing them out. If you fwrite a struct to a file or send it over a socket, the padding goes with it. That can leak whatever was in memory, which has caused real security bugs in operating system kernels. memset the struct to zero before filling in members, or serialize member by member (see Binary Files).
C
struct badly_ordered rec;
memset(&rec, 0, sizeof rec);    /* padding is now zero too */
rec.tag = 'A';
rec.count = 42;
rec.flag = 1;
fwrite(&rec, sizeof rec, 1, file);

A = {0} initializer zeroes all members, and C23 also guarantees that an empty initializer = {} zeroes the padding of the object it creates, but later assignments to the struct may still leave garbage in the holes. memset before use is the habit that's always correct.

Packed structs (a compiler extension)

GCC and Clang can remove all padding with an attribute; MSVC uses #pragma pack. This is not standard C:

C A packed struct (GCC extension)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

[[gnu::packed]] is the C23 attribute spelling; older code writes __attribute__((packed)) after the closing brace. The packed struct is 7 bytes and length sits at the misaligned offset 1.

Packed structs are tempting for file and network formats, but use them carefully:

  • Member accesses are slower on most processors, because the compiler must generate byte-by-byte loads where alignment isn't guaranteed.
  • Taking a pointer to a packed member is dangerous. uint32_t *p = &h.length; creates a misaligned uint32_t *. GCC warns with -Waddress-of-packed-member, and dereferencing it is undefined behavior that crashes on some CPUs.
  • Packing fixes padding, but not byte order (endianness) or type sizes, so a packed struct still isn't a portable file format on its own.

For external formats, reading and writing fields one at a time with fixed-width types and explicit byte order is the portable choice.

Choosing alignment with alignas

Sometimes you need more alignment than a type has by default: SIMD instructions that want 16- or 32-byte aligned data, or separating variables that different threads write to so they don't share a 64-byte cache line (called false sharing, see Multithreading). C11 added _Alignas, spelled alignas in C23 or with <stdalign.h>:

C alignas and aligned_alloc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

  • alignas(32) on a variable makes its address a multiple of 32.
  • alignas(64) on a member raises the member's and therefore the struct's alignment, so each struct counter takes a full 64 bytes and an array of four takes 256.
  • aligned_alloc(alignment, size) (C11, <stdlib.h>) returns heap memory with the alignment you ask for. The alignment must be one the implementation supports, and before C23 the size had to be a multiple of the alignment, so keep it that way for portability. Release the memory with ordinary free. (Microsoft's C runtime doesn't provide aligned_alloc; it has _aligned_malloc and _aligned_free instead.)

You can only increase alignment with alignas; asking for less than the type's natural alignment is an error.

Checking layout at compile time

When code depends on a layout, write the assumption down so the compiler checks it. static_assert (C11 _Static_assert, a keyword in C23) together with offsetof and sizeof stops the build if a change breaks the layout:

C Layout checks with static_assert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

All three checks pass, so the program compiles and runs. Change uint8_t day to uint32_t day and the build fails with static assertion failed: "amount must start at byte 8" instead of silently producing files nobody else can read. You'll meet static_assert again in Predefined Macros and assert.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On x86-64, what is sizeof of struct { char a; int b; }?

    b needs a multiple-of-4 address, so 3 padding bytes follow a, b starts at 4, and the struct is 8 bytes.
  2. 2. Why does a struct often end with padding after its last member?

    Array elements are packed back to back, so the struct size must be a multiple of its alignment for each element's members to stay aligned.
  3. 3. On x86-64, what's the smallest size you can get for a struct with members char c; double d; char e; by reordering them?

    Put d first (offset 0), then c and e at 8 and 9. That's 10 bytes of data, rounded up to a multiple of 8: 16. The original order needs 24.
  4. 4. Why is comparing two structs with memcmp unreliable?

    Padding belongs to no member and isn't set by assignments. Compare the members one by one instead.
  5. 5. What does alignas(64) long value; inside a struct do?

    alignas can raise alignment above the natural one. The struct inherits the strictest member alignment, so its size becomes a multiple of 64.

Summary

  • Every type has an alignment (a power of two); on x86-64 the basic types are aligned to their size. Ask with alignof (C23 keyword; _Alignof or <stdalign.h> in C11/C17).
  • Compilers insert padding so each member is aligned, plus trailing padding so arrays stay aligned. offsetof shows where each member starts.
  • Ordering members from largest to smallest alignment removes most padding and can save a lot of memory.
  • Padding bytes are unspecified: don't memcmp or hash structs, and memset them before writing them to files or the network.
  • [[gnu::packed]] / __attribute__((packed)) removes padding as a non-standard extension; never take pointers to packed members.
  • alignas raises alignment for variables and members; aligned_alloc returns aligned heap memory.
  • Guard layout assumptions with static_assert.

Next: The Preprocessor