Try Embedded

Structs, unions, alignment and byte order

Alignment and unaligned access, padding, packing, byte order, unions and bit-fields.

Alignment

Every type has an alignment: its address must be a multiple of that number. On most 32-bit microcontrollers the alignment equals the size, up to 4 (8 for double and uint64_t on many ABIs).

TypeSizeTypical alignment (Arm EABI)
uint8_t, char11
uint16_t22
uint32_t, float, pointers44
uint64_t, double88

Hardware cares because the bus fetches whole words. What happens on a misaligned access depends on the core:

  • Cortex-M0/M0+ (Armv6-M): any unaligned word or halfword access raises a HardFault.
  • Cortex-M3/M4/M7: ordinary loads and stores (LDR, STR, LDRH) may be unaligned but take extra cycles; LDM, STM, LDRD and exclusive accesses still fault. Setting UNALIGN_TRP in the CCR makes every unaligned access trap, which is useful for finding them.
  • Peripheral registers: must always be accessed at their natural width and alignment.

Misalignment almost never comes from ordinary variables, which the compiler aligns. It comes from reinterpreting bytes:

uint8_t rx[64];
uint32_t len = *(uint32_t *)&rx[1];   // address rx+1 is not 4-aligned: may fault, and is undefined behaviour

uint32_t ok;
memcpy(&ok, &rx[1], sizeof ok);       // correct at any alignment; compilers turn it into the best instructions

Alignment is also why structs contain padding, which is next.

Structs and the padding inside them

A struct groups related values into one object. Its members are stored in declaration order, but not necessarily back to back. Because each type has an alignment, the compiler inserts padding so that every member starts at a multiple of its own alignment.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

typedef struct {
  uint8_t flags;        // offset 0, then 3 bytes of padding
  uint32_t timestamp;   // offset 4
  uint8_t channel;      // offset 8, then 1 byte of padding
  uint16_t value;       // offset 10
} sample_t;

int main(void) {
  printf("sizeof = %u\n", (unsigned)sizeof(sample_t));
  printf("offsets: flags %u, timestamp %u, channel %u, value %u\n",
         (unsigned)offsetof(sample_t, flags), (unsigned)offsetof(sample_t, timestamp),
         (unsigned)offsetof(sample_t, channel), (unsigned)offsetof(sample_t, value));
  return 0;
}

The members add up to 8 bytes, yet the struct takes 12:

Offset01234567891011
Contentflagspadpadpadtimestamptimestamptimestamptimestampchannelpadvaluevalue

Two rules produce any layout:

  1. Each member is placed at the next offset that is a multiple of its alignment.
  2. The total size is rounded up to a multiple of the largest alignment in the struct, so that arrays of it stay aligned.

Ordering members from largest to smallest removes the interior padding. Try reordering the struct above to timestamp, value, flags, channel and run it again: it shrinks to 8 bytes.

Pitfall: Padding bytes hold whatever was in memory. memcmp on two structs, or a CRC over one, can differ even when every member is equal. Compare member by member, or memset the struct to zero before filling it.

Packing

When a struct must match an external layout exactly, such as a protocol header, padding can be switched off.

#include <stdio.h>
#include <stdint.h>
#include <string.h>

typedef struct __attribute__((packed)) {
  uint8_t type;
  uint16_t length;
  uint32_t sequence;
} header_t;

int main(void) {
  const uint8_t wire[7] = { 0x02, 0x10, 0x00, 0x78, 0x56, 0x34, 0x12 };
  header_t h;
  memcpy(&h, wire, sizeof h);
  printf("sizeof = %u, type %u, length %u, sequence 0x%08X\n", (unsigned)sizeof h, h.type, h.length, h.sequence);
  return 0;
}

#pragma pack(push, 1) before the struct and #pragma pack(pop) after it does the same job. Packing is not free:

  • Members may sit at unaligned addresses, so the compiler accesses them byte by byte, which is slower and larger.
  • Taking the address of a packed member gives a misaligned pointer that can fault when dereferenced.
  • The layout still depends on the CPU's byte order.

Pack only the structs that mirror an external format, and prefer explicit serialisation for anything that must be portable.

Byte order

A multi-byte value has to be stored in some order. Little-endian puts the least significant byte at the lowest address; big-endian puts the most significant byte there. Cortex-M, x86 and RISC-V are little-endian. Network protocols, and many sensors, are big-endian.

Value 0x12345678 stored at address AAA+1A+2A+3
Little-endian78563412
Big-endian12345678
#include <stdio.h>
#include <stdint.h>

static uint32_t read_be32(const uint8_t *p) {
  return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
}

static void write_le16(uint8_t *p, uint16_t v) {
  p[0] = (uint8_t)(v & 0xFF);
  p[1] = (uint8_t)(v >> 8);
}

int main(void) {
  uint32_t word = 0x12345678;
  const uint8_t *bytes = (const uint8_t *)&word;
  printf("in memory: %02X %02X %02X %02X\n", bytes[0], bytes[1], bytes[2], bytes[3]);

  const uint8_t packet[4] = { 0x12, 0x34, 0x56, 0x78 };
  printf("read as big-endian: 0x%08X\n", read_be32(packet));

  uint8_t out[2];
  write_le16(out, 0xABCD);
  printf("0xABCD little-endian: %02X %02X\n", out[0], out[1]);
  return 0;
}

Shifts and masks describe the format in terms of values, so the same code is correct on any CPU, at any alignment, with any padding. That is why it is preferred over casting a buffer to a struct pointer. Notice that read_be32 can read a word at an odd offset: only bytes are ever accessed.

Byte order never matters inside one CPU, where shifts and masks work on values. It matters the moment bytes cross a boundary: a network packet, a file, a sensor's register map, a CAN frame, a struct shared between two different processors.

Converting in place

htonl, ntohs and their relatives (from sockets libraries) convert between host order and network (big-endian) order. GCC and Clang provide __builtin_bswap16/32/64, which compile to a single REV instruction on Arm. Use them only on values that were already loaded safely; the shift-based functions above handle byte order and alignment in one step.

Pitfall: Overlaying a packed struct on a received buffer is common and fragile: it depends on the host's byte order, on a packing extension and on the buffer's alignment. Explicit decode functions are a few more lines and work everywhere.

Unions

A union stores all its members in the same bytes. Its size is that of its largest member. It has two uses.

Reinterpreting bytes. Write one member, read another:

#include <stdio.h>
#include <stdint.h>

typedef union {
  float f;
  uint32_t bits;
  uint8_t bytes[4];
} float_view_t;

int main(void) {
  float_view_t v;
  v.f = 1.0f;
  printf("1.0f is 0x%08X, bytes %02X %02X %02X %02X\n", v.bits, v.bytes[0], v.bytes[1], v.bytes[2], v.bytes[3]);
  return 0;
}

A cast would not do this: (uint32_t)1.0f converts the value and gives 1. Reading a union member other than the one last written is allowed in C. memcpy is the other correct way, and the only one that is also valid in C++.

Saving memory with a tagged union. When an object holds one of several kinds of data, a tag says which union member is valid. This is how a fixed-size queue item carries different message types.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

typedef enum { MSG_TEMP, MSG_BUTTON } msg_type_t;

typedef struct {
  msg_type_t type;
  union {
    int16_t temp_tenths;
    struct { uint8_t id; bool pressed; } button;
  } data;
} message_t;

static void handle(const message_t *m) {
  switch (m->type) {
    case MSG_TEMP:   printf("temperature %d.%d\n", m->data.temp_tenths / 10, m->data.temp_tenths % 10); break;
    case MSG_BUTTON: printf("button %u %s\n", m->data.button.id, m->data.button.pressed ? "down" : "up"); break;
    default:         printf("unknown message\n"); break;
  }
}

int main(void) {
  message_t a = { .type = MSG_TEMP, .data.temp_tenths = 235 };
  message_t b = { .type = MSG_BUTTON, .data.button = { 2, true } };
  handle(&a);
  handle(&b);
  printf("sizeof(message_t) = %u\n", (unsigned)sizeof(message_t));
  return 0;
}

Bit-fields

A bit-field is a struct member with a width in bits. Overlaid on a register with a union, it gives named access to each field.

#include <stdio.h>
#include <stdint.h>

typedef union {
  uint8_t raw;
  struct {
    uint8_t enable    : 1;   // bit 0
    uint8_t mode      : 3;   // bits 3..1
    uint8_t prescaler : 2;   // bits 5..4
    uint8_t           : 1;   // bit 6, reserved
    uint8_t irq       : 1;   // bit 7
  } bits;
} ctrl_t;

int main(void) {
  ctrl_t c = { .raw = 0 };
  c.bits.enable = 1;
  c.bits.mode = 5;
  c.bits.irq = 1;
  printf("raw = 0x%02X\n", c.raw);

  c.raw = 0x34;
  printf("mode = %u, prescaler = %u\n", c.bits.mode, c.bits.prescaler);
  return 0;
}

Bit-fields read well, and they come with caveats that every interviewer expects you to know:

  • The order in which fields are allocated within a unit, and whether a field may cross a unit boundary, are implementation-defined. The layout above is what GCC and Clang produce for little-endian Arm; another compiler may differ.
  • You cannot take the address of a bit-field.
  • Assigning one is still a read-modify-write of the whole unit, so it is not atomic, and it is wrong for write-1-to-clear registers.

For these reasons portable drivers, including CMSIS, use masks and shifts for hardware registers and keep bit-fields for internal data.

Passing structs around

Structs are copied when assigned, passed or returned by value. A 4-byte struct travels in a register and costs nothing. A 200-byte struct is copied onto the stack on every call, and a small MCU may have only a few hundred bytes of stack.

Pass a pointer, and make it const if the function only reads:

void motor_configure(const motor_config_t *config);   // no copy, cannot modify

C allows a = b for structs, and nothing else: there is no ==. Compare the members yourself.

Common mistakes

  • Assuming sizeof(struct) is the sum of its members.
  • Casting a byte pointer to uint32_t * at an arbitrary offset, which faults on Cortex-M0 and is undefined behaviour everywhere.
  • Sending a struct over a link with memcpy, which bakes padding, byte order and one compiler's layout into the protocol.
  • Using a bit-field layout on a different compiler or a big-endian target.
  • Reading the wrong member of a tagged union.
  • Forgetting that sizeof a struct with a flexible array member excludes the array.

Interview question: How would you safely read a big-endian 32-bit length field at offset 3 of a received packet?

Answer: Assemble it from bytes with shifts: ((uint32_t)p[3] << 24) | ((uint32_t)p[4] << 16) | ((uint32_t)p[5] << 8) | p[6]. That is independent of host endianness and never performs an unaligned access, which casting &p[3] to uint32_t * would (undefined behaviour, and a fault on Cortex-M0). An alternative is memcpy into a uint32_t followed by a byte swap if the host is little-endian.

Interview question: Why might sizeof a struct differ between two compilers or targets, and why does it matter?

Answer: Padding depends on each type's alignment, which the ABI sets: uint64_t may be 4- or 8-aligned, enums may be 1 or 4 bytes, and packing pragmas differ. It matters whenever the struct's bytes leave the program, such as writing it to flash, sending it over a link or sharing memory between cores. Fix the layout with fixed-width types, explicit ordering, _Static_assert on sizeof and offsetof, or avoid the problem with explicit serialisation.

Interview question: How do you find out at run time whether the CPU is little-endian?

Answer: Store a known multi-byte value and look at its first byte: uint16_t x = 1; bool little = *(uint8_t *)&x == 1;. Inspecting an object through an unsigned char pointer is always allowed. In practice the byte order is known at compile time, and well-written code avoids depending on it by serialising with shifts.

Interview question: When would you use a packed struct, and what are the risks?

Answer: When a struct must match an externally defined layout byte for byte, such as a file header or a wire format on a known architecture. The risks are unaligned member access (slower code, and a fault if a member's address is taken and dereferenced on a core that requires alignment), dependence on the host's byte order, and reliance on a compiler extension. For portable code, serialise each field explicitly.

In the product: a CAN car sensor

A wheel-speed sensor sends its reading in an 8-byte CAN frame, high byte first. Packing it field by field makes the bytes the same whatever the compiler does with the struct.

#include <stdio.h>
#include <stdint.h>

struct reading {
  uint16_t speed_x100;   // km/h x 100
  int8_t temp_c;
  uint8_t status;
};

int main(void) {
  struct reading r = { 8835, -5, 0x01 };
  uint8_t frame[8] = { 0 };
  frame[0] = r.speed_x100 >> 8;
  frame[1] = r.speed_x100 & 0xFF;
  frame[2] = (uint8_t)r.temp_c;
  frame[3] = r.status;
  for (int i = 0; i < 8; i++) printf("%02X ", frame[i]);
  printf("\n");
  return 0;
}

Build it: send the ride summary to the phone

This is step 6, the last of the module project. At the end of a ride the computer sends a summary to the phone app, which is written by another team in another language. Sending the struct's raw memory would send its padding and the chip's byte order too, so the summary goes out as an agreed list of bytes.

Lab: Struct layout and byte-exact serialisation

The agreed message is 12 bytes, every number little-endian (low byte first):

BytesField
0-3duration_s, uint32
4-7distance_m, uint32
8-9max_speed_x10, uint16
10avg_hr, uint8
11flags, uint8
  • summary_to_bytes(s, out) fills out[0..11] from a ride_t, byte by byte with shifts (never memcpy of the struct).
  • summary_from_bytes(in, s) does the reverse.
  • padding_bytes() returns how many bytes of padding the compiler put into the provided loose_t (its sizeof minus the sum of its members' sizes). It shows why member order matters: ride_t has none, loose_t has the same members in a worse order.

Going deeper

Interview question: Two ECUs disagree about a signal's value though both follow the same message definition. What do you check?

Answer: Byte order (Motorola versus Intel) and the bit numbering convention, signedness, scale and offset, the start bit and length, and whether either side sends a struct's raw memory with padding. Capture the frame on the bus and decode it by hand against the DBC file to see which side is wrong, then generate both sides' packing code from the same DBC so it cannot happen again.

Interview question: What is a tagged union and why is it used?

Answer: A struct containing a tag field (an enum saying which variant is stored) and a union of the possible variants. Code checks the tag before reading the matching member, giving a safe variant type in C, used for messages of several kinds, parsed tokens or values of different types. Reading a member other than the one last written is a bug that the tag helps prevent.

Interview question: How do you make the compiler verify a struct matches a datasheet layout?

Answer: Use _Static_assert (C11) on sizeof and offsetof of each important member, for example _Static_assert(offsetof(regs_t, SR) == 0x10, "SR offset");. If a member is added, removed or padded differently, the build fails instead of the code silently accessing the wrong address. Fixed-width types and explicit reserved members make the layout predictable.

Explain it: In your own words, explain why a struct is often larger than the sum of its members.

Answer: Each type has an alignment requirement, usually its size, so a 32-bit member must start at an address that is a multiple of 4. The compiler inserts padding bytes before a member when the previous members leave it misaligned, and adds padding at the end so the struct's size is a multiple of its largest alignment, keeping every element of an array aligned. Ordering members from largest to smallest alignment removes most of the padding.