Structure padding and packing

suggest change

An implementation may insert unnamed padding between structure members and after the last member so that each member meets its alignment requirement and every element of an array of the structure is correctly aligned.

struct record {
    char *name;
    char code;
    long count;
};

On a platform where pointers and long require eight-byte alignment, this layout might occupy 24 bytes: eight bytes for name, one for code, seven bytes of padding, and eight for count. The exact size and offsets are implementation-defined; do not infer them merely from whether the target is described as “64-bit.”

Reordering members can sometimes reduce padding:

struct compact_record {
    char *name;
    long count;
    char code;
};

Measure with sizeof and offsetof on every relevant target rather than assuming a layout.

Some compilers provide nonstandard packing controls, such as GCC and Clang's __attribute__((packed)) or implementation-specific pragmas. Packed members may be misaligned. Accessing them can be slower, require multiple instructions, or fault on hardware that does not support unaligned access.

Do not use an in-memory structure layout directly as a network or file format. Padding, byte order, integer widths, pointer values, and representations can differ between implementations. Serialize each field explicitly into a documented byte format. When reading a potentially unaligned field, copy its bytes into a correctly aligned object with memcpy before using the value.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents