Packing structures
suggest changeBy default structures are padded in C. If you want to avoid this behaviour, you have to explicitly request it. Under GCC it’s __attribute__((__packed__))
. Consider this example on a 64-bit machine:
struct foo {
char *p; /* 8 bytes */
char c; /* 1 byte */
long x; /* 8 bytes */
};
The structure will be automatically padded to have8-byte
alignment and will look like this:
struct foo {
char *p; /* 8 bytes */
char c; /* 1 byte */
char pad[7]; /* 7 bytes added by compiler */
long x; /* 8 bytes */
};
So sizeof(struct foo)
will give us 24
instead of 17
. This happened because of a 64 bit compiler read/write from/to Memory in 8 bytes of word in each step and obvious when try to write char c;
a one byte in memory a complete 8 bytes (i.e. word) fetched and consumes only first byte of it and its seven successive of bytes remains empty and not accessible for any read and write operation for structure padding.
Structure packing
But if you add the attribute packed
, the compiler will not add padding:
struct __attribute__((__packed__)) foo {
char *p; /* 8 bytes */
char c; /* 1 byte */
long x; /* 8 bytes */
};
Now sizeof(struct foo)
will return 17
.
Generally packed structures are used:
- To save space.
- To format a data structure to transmit over network without depending on each architecture alignment of each node of the network.
It must be taken in consideration that some processors such as the ARM Cortex-M0 do not allow unaligned memory access; in such cases, structure packing can lead to undefined behaviour and can crash the CPU.