Padding
Padding is unused bytes the compiler inserts so each struct member, and the struct as a whole, satisfies alignment. sizeof includes them. Your mental sizeof(a) + sizeof(b) often does not.
Detailed Explanation
struct { char c; int i; } is not five bytes. After c the compiler skips bytes so i lands on a 4-byte boundary. At the end it may skip more so that an array of the struct keeps every i aligned. sizeof is 8 on a typical ABI. offsetof names the member offsets. There is no standard way to name the padding itself.
Padding is not guaranteed to be zero unless you zeroed the whole object (memset, {0}, calloc). Assigning members leaves padding with indeterminate bits. memcmp of two otherwise equal structs can then fail. Compare fields, or memset before filling.
Reordering members by decreasing alignment shrinks many structs: int, int, char plus tail padding can beat char, int, int. Do not reorder a struct that is part of a file format or an ABI you already shipped. Write a packed wire format with explicit bytes instead.
Bit-fields have their own packing rules, implementation-defined in enough places that portable code avoids them on the wire. #pragma pack and __attribute__((packed)) reduce padding and create misaligned members. They are extensions.
Sending a struct across the network by fwrite(&s, sizeof s, 1, fp) ships the padding and the host endianness. That is a bug unless both ends are the same ABI and you said so. Serialize field by field.
Code Examples
#include <stdio.h>
#include <stddef.h>
struct Loose {
char c;
int i;
char d;
};
struct Tight {
int i;
char c;
char d;
};
int main(void)
{
printf("%zu %zu\n", sizeof(struct Loose), sizeof(struct Tight));
/* typical: 12 8 */
printf("i@%zu\n", offsetof(struct Loose, i));
/* typical: 4 */
return 0;
}#include <stdio.h>
#include <string.h>
struct S { char c; int i; };
int main(void)
{
struct S a, b;
memset(&a, 0, sizeof a);
memset(&b, 0xff, sizeof b);
a.c = b.c = 1;
a.i = b.i = 2;
printf("%d\n", memcmp(&a, &b, sizeof a) == 0);
/* prints: 0 — padding in b is 0xff */
return 0;
}Common Gotchas
`memcmp` on structs is not field equality
padding bits may differ.
Reordering members to save RAM changes ABI
existing `.o` files and file formats break.
Tail padding exists so `s[1]` stays aligned
`sizeof` is not "the last member plus its size."
Dumping a struct to disk is not a portable format
padding and endianness travel with it.