EMBEDDED TOOLKIT

SYSTEMS R&D // DEV_TOOLS SUITE

Tools (65)

struct padding memory layout

SYSTEM ONLINE

Struct Definition (C/C++)

Memory Layout

sizeof(struct) = 12 bytes
+0
id (char)
1 b
+1
PADDING
3 b
+4
temperature (int)
4 b
+8
humidity (short)
2 b
+10
status (char)
1 b
+11
TRAILING PADDING
1 b

📖 Struct Padding & Alignment

C/C++ compilers add empty bytes (padding) between struct fields to align them in memory to machine word boundaries (e.g. 4 bytes in 32-bit ARM). This increases hardware read speed at the cost of wasting RAM.

  • Padding: Wastes memory. To reduce it, group types from largest to smallest (e.g. pointers/long -> int -> short -> char).
  • #pragma pack(1): Forces no padding. Ideal when copying struct directly via UART or uDPA. Note: In ARM architectures (e.g. Cortex-M0), Unaligned Access can cause a HardFault!