Consider:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
The sizes of the structures are 12 and 8 respectively.
Are these structures padded or packed?
When does padding or packing take place?
Padding aligns structure members to “natural” address boundaries – say,
intmembers would have offsets, which aremod(4) == 0on 32-bit platform. Padding is on by default. It inserts the following “gaps” into your first structure:Packing, on the other hand prevents compiler from doing padding – this has to be explicitly requested – under GCC it’s
__attribute__((__packed__)), so the following:would produce structure of size
6on a 32-bit architecture.A note though – unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.