Structure Padding
suggest changeAn implementation may insert unnamed padding between structure members and after the final member to satisfy alignment requirements. For example, on an implementation where int is four bytes with four-byte alignment and short is two bytes with two-byte alignment:
struct example {
int a;
short b;
int c;
};
One common layout is:
int aat offset 0, with size 4;short bat offset 4, with size 2;- two padding bytes at offsets 6 and 7;
int cat offset 8, with size 4.
In that implementation, sizeof(struct example) is 12. The exact size, alignment, member offsets, and amount of padding are implementation-defined; do not infer them solely from whether the target is described as 32-bit or 64-bit.
Use sizeof to obtain the complete structure size, _Alignof (or C23 alignof) to obtain its alignment requirement, and offsetof from <stddef.h> to inspect member offsets. Storage returned by malloc, calloc, or realloc is suitably aligned for any object type with a fundamental alignment requirement.
Padding bytes can hold unspecified values. Consequently, comparing structures with memcmp, hashing their raw representations, or writing them directly to a file or network connection is generally not portable. Serialize individual members instead.