</>EmbeddedInterview

What is structure padding and how do you avoid it?

MediumC Programming

Short answer: The compiler inserts unused padding bytes between members (and at the end) so that each member starts at an address that is a multiple of its alignment, and so that arrays of the struct keep every element aligned. To reduce padding, order members from largest alignment to smallest. To remove it entirely, use __attribute__((packed)) or #pragma pack(1), but packed members may be accessed unaligned, which is slower and can fault on some cores.

struct a { char c; int i; char d; };   /* 12 bytes on 32-bit Arm */
/* offset: c 0, padding 1-3, i 4-7, d 8, padding 9-11 */

struct b { int i; char c; char d; };   /* 8 bytes */
/* offset: i 0-3, c 4, d 5, padding 6-7 */

Why the trailing padding in struct b? The struct's alignment is 4 (its largest member). In an array struct b arr[2], arr[1].i must be 4-byte aligned, so the size is rounded up to a multiple of 4.

Checking layout

#include <stddef.h>
_Static_assert(offsetof(struct b, c) == 4, "layout changed");
_Static_assert(sizeof(struct b) == 8, "size changed");

pahole (from dwarves) prints the layout and holes of every struct in an ELF file with debug info.

Packed structs and their costs

struct __attribute__((packed)) hdr { uint8_t type; uint32_t len; };   /* 5 bytes */
  • Accessing len needs an unaligned access. Cortex-M3/M4/M7 handle unaligned 32-bit loads in hardware (slower); Cortex-M0/M0+ and older Arm cores fault, so the compiler must generate byte-by-byte accesses (correct but slower and larger).
  • Taking the address of a packed member (uint32_t *p = &h.len;) and using it as a normal pointer can produce unaligned accesses the compiler does not know about (GCC warns with -Waddress-of-packed-member).
  • Packed structs are fine for matching a wire format when you also handle endianness; many projects still prefer explicit serialisation with shifts and memcpy.

Memory saving on MCUs: reordering members in large arrays of structs can save a significant amount of RAM with no runtime cost.