packed is a variable attribute that is used with structures and unions in order to minimize the memory requirements.
#include <stdio.h>
struct foo {
int a;
char c;
};
struct __attribute__((__packed__))foo_packed {
int a;
char c;
};
int main()
{
printf("Size of foo: %d\n", sizeof(struct foo));
printf("Size of packed foo: %d\n", sizeof(struct foo_packed));
return 0;
}
On my 64 bit Linux,
- Size of struct foo = 8 bytes
- Size of struct foo_packed = 5 bytes
struct t
with no attributes and default alignment on 8-byte boundary:+-+-------+--+-------+
|a| |bb| |
+-+-------+--+-------+
struct t
when a and b are aligned on 16-byte boundaries:+-+---------------+--+---------------+
|a| padding |bb| padding |
+-+---------------+--+---------------+
struct t
when a and b have no alignment restrictions and t is packed:+-+--+
|a|bb|
+-+--+