The idea: every field starts at a multiple of its alignment

A struct is a block of bytes. The compiler gives each field an offset from the start of the block, in the order you wrote the fields. But it can't always put a field right after the one before. Each type has an alignment: an int must start at an address that is a multiple of 4, a double at a multiple of 8. When the next free offset is not a multiple, the compiler skips bytes. Those unused bytes are padding. So struct Mixed { char c; double d; int i; } holds 13 bytes of data but takes 24 (Demo: char, double, int → 24 bytes).

struct Mixed laid out in 24 bytes, three rows of 8. Row 0: c at offset 0, then 7 padding bytes at 1 to 7. Row 1: d fills offsets 8 to 15. Row 2: i at 16 to 19, then 4 bytes of trailing padding at 20 to 23. 13 bytes of data, 11 of padding.
13 bytes of data, 24 bytes of struct: 7 bytes of padding before the double and 4 at the end.

Size and alignment of each type

On the usual 64-bit systems (Linux and macOS on x86-64 and arm64, the LP64 model) a basic type is aligned to its own size:

TypeSize (bytes)Alignment
char11
short22
int, float44
long, double, any pointer88
a structits sizeofthe largest alignment of its fields

The CPU loads an aligned value in one access, and it never crosses a cache line. That is why the ABI asks for it. On 32-bit x86 Linux a double inside a struct is aligned to 4 only, and Windows has long = 4 bytes, so the numbers on this page are for LP64.

The rule: round the cursor up

The compiler keeps an offset cursor that starts at 0. For each field, in order:

  1. Round the cursor up to the field's alignment. The bytes skipped are padding.
  2. Put the field there, and move the cursor past it.

After the last field, round the cursor up once more, to the struct's own alignment (its largest field alignment). That is sizeof, and the bytes added are trailing padding. For struct Small { char c; int i; char d; }: c at 0, round 1 up to 4, i at 4–7, d at 8, end at 9, round up to 12 (Demo: char, int, char → 12 bytes). Half of the 12 bytes are padding. The C standard lets padding go after any field, never before the first one, so the struct's address is always the address of its first field.

Why arrays need trailing padding

In struct Mixed arr[2] the elements sit back to back, exactly sizeof apart. With the 4 trailing bytes, arr[1] starts at 24 and arr[1].d at 32, a multiple of 8. Without them sizeof would be 20 and arr[1].d would land at 28, misaligned (Demo: array of 2). This is why sizeof is always a multiple of the struct's alignment, and why malloc(n * sizeof(struct Mixed)) gives an array whose every element is aligned. Pointer arithmetic such as p + 1 steps by that same sizeof; C++ Pointers animates that part.

Reorder the fields to shrink the struct

C never moves fields for you: the order you write is the order in memory. You can move them yourself. Put the fields with the largest alignment first. Every size is a multiple of its own alignment, and every alignment is a power of two, so after an 8-byte field the cursor is still a multiple of 4, 2 and 1. No gap is needed between the fields, and only trailing padding can remain. Mixed goes from 24 to 16 bytes, and Record, with 5 fields, from 32 to 16 (Demo: sort the fields largest first, Demo: 5 fields, half padding).

Before: struct Record with tag, val, flag, id, n in source order takes 32 bytes, 16 of them padding: tag at 0, 7 padding bytes, val at 8 to 15, flag at 16, 3 padding bytes, id at 20 to 23, n at 24 to 25, 6 bytes of trailing padding. After sorting by alignment, val at 0 to 7, id at 8 to 11, n at 12 to 13, tag at 14, flag at 15: 16 bytes, no padding.
The same five fields, largest alignment first: 32 bytes become 16, with no padding left.

Sorting can't remove trailing padding. struct Pixel { int x; int y; char color; } is already sorted and still takes 12 bytes for 9 of data, because 12 is the next multiple of 4 (Demo: sorting can't remove trailing padding). Saving 8 bytes per struct matters when there are millions of them: a smaller struct means more of them per 64-byte cache line (see How a CPU Cache Finds, Misses and Replaces). Sometimes you keep a worse order on purpose, for example to keep the fields used together in the same cache line, or to keep a file or network layout.

#pragma pack and what it costs

#pragma pack(1) (GCC and Clang also accept __attribute__((packed))) tells the compiler to treat every alignment as 1. All padding goes: Mixed takes 13 bytes, exactly its data. But d now sits at offset 1 and i at 9, and in an array arr[1].d lands at 14 (Demo: #pragma pack(1)). The costs:

  • The compiler must emit loads that work at any address. On x86 they work but can be slower, especially when a value crosses a cache line. Some CPUs and some instructions (older ARM, atomics, SIMD aligned loads) fault on a misaligned address.
  • &s.d is a double * that is not aligned. Passing it to code that expects a normal double * is undefined behaviour; GCC and Clang warn with -Waddress-of-packed-member.
  • Atomic operations on a misaligned field are very slow (on x86 a "split lock" that crosses a cache line stalls other cores) or fault outright on other CPUs.

Packing is for byte layouts fixed by someone else: file headers and network packets. Even there, many programs read the bytes into a normal struct field by field instead. Byte order inside each field is a separate question, shown on Little-endian vs big-endian.

Checking a layout yourself

ToolWhat it tells you
sizeof(struct S)total size, trailing padding included
offsetof(struct S, f) (<stddef.h>)offset of field f
alignof(struct S) (C11 <stdalign.h>, C++11)the struct's alignment
_Static_assert(sizeof(struct S) == 16, "...")fails the build if the layout changes
gcc -Wpaddeda warning for each place padding is added
pahole (dwarves)prints every struct of a binary with its holes

The numbers on this page were checked with sizeof, offsetof and alignof compiled by Clang on arm64; x86-64 Linux gives the same.

Common mistakes

  • "sizeof is the sum of the field sizes." Only with no padding. Mixed sums to 13 and is 24.
  • "The compiler reorders fields to save space." Not in C, and not in C++ for fields with the same access. Rust does reorder.
  • Comparing structs with memcmp. Padding bytes hold whatever was there before, so two equal structs can compare unequal. Compare field by field.
  • Writing a struct to a file or socket as raw bytes. The padding (possibly old data from the stack or heap) goes out too, and another compiler or ABI may lay it out differently.

See also Stack vs heap in C for where a struct lives, C++ virtual functions: the vptr and the vtable for the hidden pointer a C++ class with virtual functions adds at offset 0, and MESI cache coherence and false sharing for fields of one struct fighting over a cache line.

What the page leaves out

Bit-fields, unions, flexible array members, nested structs (a nested struct is just a field with its own size and alignment), alignas and over-aligned types, long double (16 bytes on x86-64 Linux), 32-bit and Windows ABIs, C++ classes with base classes or virtual functions, and empty structs (size 1 in C++). The cost of a misaligned access is described, not measured.

On the mind map

Open the Operating Systems mind mapOperatingSystemsBoot and program start: from power on to main()Boot and program startProcesses and the kernel: how user code talks to the kernelProcesses and the kernelInterrupts and devices: hardware interrupts the CPUInterrupts and devicesScheduling and deadlock: who runs next, who gets whatScheduling and deadlockVirtual memory: every address is translatedVirtual memoryPhysical memory: who gets which bytes of RAMPhysical memoryFiles and storage: from open() down to the diskFiles and storageDisks and RAID: blocks down to platter or flashDisks and RAIDIsolation and security: limit what a process can doIsolation and securityStack vs heap in CStack vs heap in Cframes pop on return, malloc needs freeC++ PointersC++ Pointersp holds an address; p + 1 adds sizeofStruct paddingLargest alignment first leaves no gapsEndiannessEndiannessx86 stores the low byte firstBuddy allocatorBuddy allocatorsplit in halves, find the buddy with XORFit StrategiesFit Strategiesfirst, next, best, worst: none always winsReclaim and OOM killerReclaim and OOM killerkswapd reclaims, then the OOM killerSlab allocatorSlab allocatorkmalloc: per-CPU freelists of fixed sizesmalloc vs jemalloc vs tcmallocmalloc vs jemalloc vs tcmallocper-thread caches avoid arena lock fightsSwap out and swap inSwap out and swap inCold anon pages go to disk, fault backOpen the Operating Systems mind mapOperating Systemswho gets which bytes of RAMPhysical memoryStack vs heap in CStack vs heap in Cframes pop on return, malloc needs freeC++ PointersC++ Pointersp holds an address; p + 1 adds sizeofStruct paddingLargest alignment first leaves no gapsEndiannessEndiannessx86 stores the low byte firstBuddy allocatorBuddy allocatorsplit in halves, find the buddy with XORFit StrategiesFit Strategiesfirst, next, best, worst: none always winsReclaim and OOM killerReclaim and OOM killerkswapd reclaims, then the OOM killerSlab allocatorSlab allocatorkmalloc: per-CPU freelists of fixed sizesmalloc vs jemalloc vs tcmallocmalloc vs jemalloc vs tcmallocper-thread caches avoid arena lock fightsSwap out and swap inSwap out and swap inCold anon pages go to disk, fault back
This page on the Operating Systems mind map · 64 pages in 9 branches · open it to see the whole map and test yourself in recall mode.