Section 4.27

Struct padding and packing

Definition

Struct padding is unused bytes that a C compiler inserts into a structure, between members or after the last member, so that every member starts at an address its type’s alignment §4.22 allows: a multiple of a fixed power of two, such as 4 for a 4-byte integer on most processors. A structure, declared with struct, is a C type that groups named members in declaration order. Packing is a compiler extension that removes this padding, so members may sit at misaligned addresses.

The idea

A program keeps a one-byte tag and a four-byte count in one structure, struct msg { uint8_t tag; uint32_t count; };, where uint8_t and uint32_t are C’s unsigned integer types of exactly 8 and 32 bits. The members need 1+4=51 + 4 = 5 bytes, yet on the usual platforms for 64-bit x86 and 32-bit Arm processors sizeof(struct msg), the structure’s size in bytes, is 8. The cause is how processors read memory. Many read a 4-byte integer in one step only from an address that is a multiple of 4, and some raise a fault, a hardware error that stops the access, at any other address. So the compiler skips the 3 bytes after the tag and starts the count 4 bytes into the structure.

A shelf marked every 4 centimeters is the picture: each large box must start at a mark, so a small box before it leaves a gap. Shelves standing end to end, as array §14.5 elements do, must each end at a mark too; that end gap is tail padding. The picture stops in one place: the compiler never rearranges the boxes to close the gaps, because C keeps members in declaration order. Only the programmer can reduce padding, by reordering members or by packing.

Packing is for cases where the gaps are unwanted, such as very tight memory, or a wish to make the structure’s bytes match a file or message format. It closes the gaps and nothing else. It does not change the endianness §4.21 of the count, the order in which a multi-byte number’s bytes are stored: little-endian processors store the least significant byte first, big-endian processors the most significant byte first.

How it works

The layout rules come from the platform’s ABI §12.47 (application binary interface): the agreement, shared by the compilers for that platform, on the size and alignment of each type, the layout of structures and the way functions are called. C itself fixes only a few rules, listed under “Stated precisely”. Common ABIs lay out a structure as follows; the offset of a member is its distance in bytes from the start of the structure.

  1. Start at offset 0.

  2. For each member in declaration order, round the current offset up to the next multiple of the member’s alignment, place the member there, and add its size. The bytes skipped are padding.

  3. Round the final offset up to a multiple of the structure’s alignment, which is the largest alignment of any member. The bytes added are tail padding, and the result is sizeof of the structure.

Tail padding is needed because C places array elements back to back: element ii starts ii element sizes after the first, so a size that is not a multiple of the alignment would misalign the second element. Ordering members by decreasing alignment removes all padding between members. Each member’s size is a multiple of its own alignment, so every member then ends at a multiple of the next, smaller or equal, power-of-two alignment, and only tail padding can remain.

Packing is requested with __attribute__((packed)), which the widely used compilers gcc and clang accept, or with #pragma pack(1), which Microsoft’s C compiler, gcc and clang all accept; neither is standard C. A packed structure has alignment 1 and no padding, so the count in struct msg moves to offset 1. Code that reads m.count, where m is a packed struct msg, gets instructions that work at any address, often several single-byte loads. A pointer to the member loses that knowledge: after uint32_t *p = &m.count;, reading *p is a misaligned access, which is undefined behavior §4.12 in C and a fault on processors that require alignment.

C also lets a member occupy a stated number of bits, a bit-field: in struct r { unsigned int lo : 4; unsigned int hi : 4; }; each member is 4 bits wide. Most of the bit-field layout is implementation-defined behavior §4.13, meaning that each compiler chooses it and documents the choice: which storage unit holds the bits, whether a bit-field that does not fit in the rest of a unit continues into the next unit, and whether the first bit-field takes the low-order or the high-order bits of the unit. Common compilers for little-endian processors start at the low-order bit, those for big-endian processors at the high-order bit. To read a 4-bit field from a byte b of a fixed format, code therefore uses a bit mask §4.50, a value whose 1 bits select the bits to keep, and a shift: lo = b & 0x0F; and hi = (b >> 4) & 0x0F; mean the same with every compiler.

Worked example

Take struct a { uint8_t x; uint32_t y; uint16_t z; }; on an ABI where each of these types has an alignment equal to its size, 1, 4 and 2 bytes, as on the usual 64-bit x86 and 32-bit Arm platforms.

  1. x goes at offset 0 and occupies 1 byte. The next free offset is 1.

  2. y needs a multiple of 4. The first multiple of 4 at or above 1 is 4, so offsets 1, 2 and 3 are padding, 4−1=34 - 1 = 3 bytes. y occupies offsets 4 to 7, and the next free offset is 8.

  3. z needs a multiple of 2, and 8 is one, so z occupies offsets 8 and 9. The next free offset is 10.

  4. The structure’s alignment is the largest of 1, 4 and 2, which is 4. The first multiple of 4 at or above 10 is 12, so offsets 10 and 11 are tail padding.

sizeof(struct a) is 12 bytes: 1+4+2=71 + 4 + 2 = 7 bytes of members and 3+2=53 + 2 = 5 bytes of padding.

Reordered as struct b { uint32_t y; uint16_t z; uint8_t x; };, the members occupy offsets 0 to 3, 4 to 5, and 6, and the end, 7, rounds up to 8. The size is 8 bytes, with 1 byte of tail padding, and an array of 1000 such structures shrinks from 1000×12=12,0001000 \times 12 = 12{,}000 bytes to 1000×8=80001000 \times 8 = 8000 bytes.

The same source code can have different layouts on different ABIs. struct c { char k; double d; }; is 16 bytes, with d at offset 8, on 64-bit x86 Linux. It is 12 bytes, with d at offset 4, on 32-bit x86 Linux, whose ABI aligns a double inside a structure to 4 bytes only.

Packing does not create a message format. Let a format define 5 bytes: the tag, then the count as a 4-byte big-endian number. Tag 1 and count 258, which is 1×256+21 \times 256 + 2, or 0x00000102 in hexadecimal, must become 01 00 00 01 02. On a little-endian machine the unpacked struct msg holds 01 ?? ?? ?? 02 01 00 00, where ?? marks a padding byte of unspecified value. The packed version holds 01 02 01 00 00: no gap, but the count is still in the machine’s byte order, not the format’s.

The byte 0x31, binary 0011 0001, holds two 4-bit fields. The mask-and-shift expressions above give 1 for lo and 3 for hi with every compiler. Copied into struct r, the same byte reads as lo 1 and hi 3 with a compiler that starts at the low-order bit, but as lo 3 and hi 1 with a compiler that starts at the high-order bit. The Linux kernel’s structure for the IPv4 (Internet Protocol version 4) header declares its two 4-bit fields in opposite orders under a byte-order test for exactly this reason.

Stated precisely

The C standard (C11, section 6.7.2.1 and related sections) guarantees the following about a structure’s layout; the ABI fixes the rest.

The layout rule of common ABIs can be written exactly. For an alignment AA, which is a power of two, rounding an offset nn up gives up(n,A)=⌈n/A⌉×A\mathrm{up}(n, A) = \lceil n / A \rceil \times A, the smallest multiple of AA that is at least nn; here ⌈x⌉\lceil x \rceil means xx rounded up to a whole number. Let the members, in declaration order, have sizes s1,…,sks_1, \dots, s_k and alignments A1,…,AkA_1, \dots, A_k. Member 1 has offset o1=0o_1 = 0, and member i>1i > 1 has offset oi=up(oi−1+si−1,Ai)o_i = \mathrm{up}(o_{i-1} + s_{i-1}, A_i). The structure’s alignment is A=max(A1,…,Ak)A = \max(A_1, \dots, A_k), and its size is up(ok+sk,A)\mathrm{up}(o_k + s_k, A). The padding is that size minus s1+…+sks_1 + \dots + s_k. Packing sets every AiA_i to 1, so the size becomes the plain sum.

A program states its layout assumptions in code and has the compiler check them. The macro offsetof, from the header stddef.h, gives a member’s offset: offsetof(struct msg, count) is 4 on the platforms above. The declaration _Static_assert(sizeof(struct msg) == 8, "size"); stops the build on any platform where the assumption is false.

Limits and common mistakes

Padding leaks data. Writing a structure’s memory image to a file, a network or a less privileged program also sends its padding bytes, which may hold old data such as values left on the stack; operating system kernels have repeatedly leaked memory to user programs this way. Clearing the structure with memset first works with common compilers, but standard C does not promise that the padding stays zero after members are assigned. Writing the members one by one into a byte buffer sends exactly the intended bytes.

Raw comparison sees the padding. Comparing two structures with memcmp, hashing them, or computing a message authentication code §5.7 over their memory includes the padding bytes, so two structures with equal members can give different results.

Packing is not a format. Besides the machine’s byte order, shown in the worked example, a packed structure keeps the machine’s sizes for types such as int and the compiler’s bit-field order. Reading a received buffer through a pointer to a packed structure can also break C’s strict aliasing rule §4.23, which limits the types through which an object’s bytes may be read. Portable code writes and reads each field explicitly, as described under serialization §4.28.

Packing costs speed and indivisibility. Without hardware support for misaligned loads, each access to a packed member becomes several byte loads, and a value read in two parts can be seen half updated by a concurrent writer such as an interrupt handler §6.12.

Changing a layout changes the ABI. Reordering or packing a structure that separately compiled code already uses changes the offsets that code expects, without any error message. A #pragma pack that a header file does not reset also changes every structure declared after it.

Questions answered

Why can sizeof(struct) exceed the sum of field widths?

sizeof of a structure can exceed the sum of its members’ sizes because the compiler inserts padding bytes and sizeof counts them. Padding between members moves each member to an offset that is a multiple of its alignment, the power of two that the member’s address must be a multiple of. Padding after the last member makes the size a multiple of the structure’s alignment, the largest alignment among its members, so that every element of an array of the structure is aligned too. For example, struct { uint8_t x; uint32_t y; uint16_t z; } is 12 bytes on the usual 64-bit x86 and 32-bit Arm platforms: 7 bytes of members, 3 bytes of padding before y and 2 bytes after z. The C standard allows padding after any member but not before the first; the platform’s application binary interface (ABI) fixes the amount. Ordering members from largest to smallest alignment reduces the padding, and a compiler-specific packing attribute removes it, at the cost of misaligned members.

Related entries: Alignment (§4.22), Serialization (§4.28), Guest-host ABI (§2.37), Implementation-defined behavior (§4.13), Endianness (§4.21), Strict aliasing and effective type (§4.23). Further reading: [78].