Skip to content
systemcoding.dev
Toolchains

Pack Structs With __attribute__((packed)) and Know the Costs

Remove struct padding with __attribute__((packed)) to match a wire format, then see the unaligned-access cost, the pointer warning and the memcpy alternative.

6 min read
Summarize in AI
Flat illustration of a memory cell holding the address of another cell, with the GNU, C and C++ logos.

A C compiler inserts padding bytes into a struct so each member sits at an address its type prefers. That is the right default for speed, and the wrong one when a struct has to match bytes that someone else defined: a network header, a file format, a device register block, a message from a microcontroller. __attribute__((packed)) tells GCC and Clang to drop the padding. It solves the layout problem and quietly creates others, because the members are no longer aligned and the compiler's assumptions about pointers to them stop holding. This post shows what packing does to size and offsets, what the generated code looks like, the warning that tells you about the pointer hazard, and a safer pattern for most cases. The examples use GCC 14 on x86-64 and AArch64.

What the padding does

Every type has an alignment requirement. On x86-64 and AArch64 a uint32_t wants a four-byte boundary and a uint64_t wants an eight-byte boundary. A struct's own alignment is the largest alignment of any member, and its size is rounded up to a multiple of that. The compiler adds padding between members to satisfy each member, and at the end to satisfy the struct.

layout.cc
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

struct loose {
    uint8_t  kind;
    uint32_t length;
    uint16_t flags;
};

struct tight {
    uint8_t  kind;
    uint32_t length;
    uint16_t flags;
} __attribute__((packed));

int main(void)
{
    printf("loose: size=%zu length@%zu flags@%zu align=%zu\n",
           sizeof(struct loose), offsetof(struct loose, length),
           offsetof(struct loose, flags), _Alignof(struct loose));
    printf("tight: size=%zu length@%zu flags@%zu align=%zu\n",
           sizeof(struct tight), offsetof(struct tight, length),
           offsetof(struct tight, flags), _Alignof(struct tight));
    return 0;
}
Text
loose: size=12 length@4 flags@8 align=4
tight: size=7 length@1 flags@5 align=1

The loose struct puts three bytes of padding after kind so length lands on offset 4, then two after flags to round the size to 12. The packed one has no padding at all: seven bytes, every member at the next free byte, and an alignment of 1, which is why it can sit at any address in memory.

Spelling and scope

The attribute goes after the closing brace of a struct definition, as above, or on the struct keyword before the tag. It applies to the whole struct. You can also pack a single member:

c
struct mixed {
    uint8_t  kind;
    uint32_t length __attribute__((packed));
    uint16_t flags;
};

That removes the padding before length but leaves flags aligned and the struct padded at the end, which is rarely what you intend, so most code packs the whole struct. Clang accepts the same spelling. C23 has no standard equivalent. MSVC and some embedded compilers use #pragma pack(push, 1) and #pragma pack(pop), which GCC also supports for compatibility and which affects every struct declared between the two lines. GCC's -fpack-struct option packs every struct in the program, changes the ABI and breaks the C library's own types, so do not use it.

What packed does to the generated code

Packed members can sit at any address, so the compiler can no longer use an aligned load for them. On x86-64 that costs nothing in correctness, since the CPU accepts unaligned loads, and a little in speed when a load crosses a cache line. On architectures that fault on unaligned access, or that need multiple instructions to do it safely, the difference shows in the assembly:

read.cc
#include <stdint.h>

struct hdr {
    uint8_t  kind;
    uint32_t length;
} __attribute__((packed));

uint32_t get_length(const struct hdr *h)
{
    return h->length;
}

On x86-64, gcc -O2 -S produces a single instruction:

Text
get_length:
	movl	1(%rdi), %eax
	ret

On an Armv6-M Cortex-M0, which has no unaligned load instruction, -mcpu=cortex-m0 -mthumb -O2 makes the compiler load the four bytes separately and combine them, a sequence of ldrb and shift instructions. The packed attribute is how the compiler knows to generate that correctly, and it is why a plain pointer cast to the same address would be a bug. Armv7-M and later cores allow unaligned ldr for normal memory, with some exceptions for device memory and multi-word loads, so the code size differs by core.

The cost, in short: more instructions on strict-alignment targets, a possible cache-line split on any target, and no atomicity guarantee. An unaligned 32-bit store is not atomic on most CPUs, so a packed field shared between threads or an interrupt handler needs a lock or an explicit copy.

The pointer hazard

The packed attribute makes the members misaligned but leaves their types alone. If you take the address of a member, you get an ordinary uint32_t *, which the compiler assumes is aligned. Passing it to a function or dereferencing it can produce a faulting instruction. GCC warns about the hazard with -Waddress-of-packed-member, enabled by default since GCC 9:

ptr.cc
#include <stdint.h>
#include <stdio.h>

struct hdr {
    uint8_t  kind;
    uint32_t length;
} __attribute__((packed));

int main(void)
{
    struct hdr h = { 1, 99 };
    uint32_t *p = &h.length;
    printf("%u\n", *p);
    return 0;
}
Text
ptr.c: In function 'main':
ptr.c:12:19: warning: taking address of packed member of 'struct hdr' may result in an unaligned pointer value [-Waddress-of-packed-member]

On x86-64 the program prints 99, because the CPU tolerates the misalignment. On a strict-alignment target, or under UBSan with -fsanitize=alignment, the same code faults. Read the warning as a defect, not noise.

The safer pattern: copy, do not cast

For wire formats, many projects do not pack the struct at all. They read the bytes into a local buffer and copy each field out with memcpy, which is portable, never misaligned and, on compilers that recognize it, compiles to the same single load as the packed version on x86-64:

parse.cc
#include <stdint.h>
#include <string.h>

struct hdr {
    uint8_t  kind;
    uint32_t length;
};

void parse(const unsigned char *buf, struct hdr *out)
{
    out->kind = buf[0];
    memcpy(&out->length, buf + 1, sizeof out->length);
}

The in-memory struct is normal, aligned and fast to use. The wire layout lives in parse, where byte order and offsets are explicit. If the wire format is big-endian, add a __builtin_bswap32 or the ntohl call there. This pattern keeps the packed layout out of the rest of the program, where it would spread through every function that touches the struct.

Use packed when the struct is a view over memory you do not own and cannot copy: a memory-mapped file, a DMA descriptor, a hardware register block with odd offsets. Use the copy pattern when you parse a stream.

Checking your layout at compile time

A packed struct is only correct if its size matches the format. Assert it, so a changed field or a compiler flag cannot silently break the layout:

c
_Static_assert(sizeof(struct hdr) == 5, "hdr must be 5 bytes");
_Static_assert(offsetof(struct hdr, length) == 1, "length at offset 1");

_Static_assert is standard since C11, and static_assert since C23. With the assertion in place, a build fails at the point where someone adds a field, not three weeks later in a protocol test.

Costs to weigh

  • Speed. Unaligned access can cost extra cycles, particularly across a cache line or a page boundary. We have not measured a specific number here, and it varies by core; benchmark your access pattern.

  • Code size. Strict-alignment cores emit byte-wise sequences, which makes hot paths larger.

  • Atomicity. Misaligned loads and stores are not atomic. Do not share packed fields between threads without a lock.

  • Portability. __attribute__((packed)) is a GNU extension. The #pragma pack form is more widely accepted but affects subsequent declarations.

  • Bitfields. Bit-field layout in a packed struct is implementation-defined, and the packed attribute does not make it portable across compilers.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.