
You flash the firmware, hit run, and the MCU immediately crashes into a HardFault handler. The debugger shows the fault occurred inside memcpy - or worse, inside a simple struct assignment that the compiler lowered to a word copy. The stack trace is useless, the variables look fine, and there is no obvious null pointer. Welcome to the world of unaligned memory access faults on ARM Cortex-M.
This article walks through why memcpy (and innocent-looking struct copies) trigger HardFaults on Cortex-M, how to definitively identify the fault cause using the CFSR register, and the practical fixes: compiler flags, MPU configuration, and safe copy patterns that work across Cortex-M0 through M7.
+-----------------------------------------------------------------------------+| CORTEX-M UNALIGNED MEMORY ACCESS & FAULT PATHS |+=============================================================================+| || [ SCENARIO 1: Default Optimization (-O2, -munaligned-access) ] || || Source Code Compiler Emits CPU Execution || -------------------- -------------------- ------------------- || memcpy(dst, src, 4); -> LDR r0, [r1] -> Cortex-M0 / M0+: || (or struct copy) STR r0, [r2] HardFault (Direct) || (32-bit single word) || -> Cortex-M3 / M4 / M7: || - If UNALIGN_TRP = 1 || - Or Device Memory || => UsageFault (UFSR) || (Escalates to HF) || || struct copy -> LDMIA r1!, {r0-r3} -> ALL Cortex-M Cores: || (multi-word payload) STMIA r2!, {r0-r3} HardFault || (Multi-register access (Strictly requires || lacks unaligned support) 4-byte alignment) || || +-------------------------------------------------------------------------+ || || [ SCENARIO 2: Hardened with -mno-unaligned-access or safe_memcpy() ] || || Source Code Compiler Emits CPU Execution || -------------------- -------------------- ------------------- || memcpy(dst, src, 4); -> LDRB r0, [r1] -> ALL Cortex-M Cores: || (or safe_memcpy()) LDRB r3, [r1, #1] SUCCESS (No Fault) || LDRB ip, [r1, #2] - Byte-by-byte bus || LDRB lr, [r1, #3] transactions || STRB r0, [r2]... - Immune to pointer || (Byte-wise transfers) misalignment || |+-----------------------------------------------------------------------------+
You are copying a protocol packet into a local struct, moving data between DMA buffers, or initializing a peripheral data block. The code looks perfectly valid:
typedef struct __attribute__((packed)) {uint8_t header; /* Offset 0, 1 byte */uint32_t payload_len; /* Offset 1, 4 bytes (unaligned!) */uint16_t crc; /* Offset 5, 2 bytes (unaligned!) */} packet_t; /* Total packed size = 7 bytes */void process_packet(const uint8_t *raw, size_t len) {packet_t pkt;memcpy(&pkt, raw, sizeof(pkt)); /* CRASH HERE on Cortex-M0 / unaligned raw *//* ... */}
+-----------------------------------------------------------------------------+| 32-BIT WORD ALIGNMENT VS PACKED STRUCT MEMORY LAYOUT |+=============================================================================+| || Word 0 Address: 0x20000000 (Aligned 4-Byte Word Boundary) || +-------------------+-------------------+-------------------+-------------+ || | Byte 0 (Offs +0) | Byte 1 (Offs +1) | Byte 2 (Offs +2) | Byte 3 | || | header (uint8_t) | payload_len[0] | payload_len[1] | payload_ | || | (1 byte) | (byte 0 of u32) | (byte 1 of u32) | len[2] | || +-------------------+-------------------+-------------------+-------------+ || ^ ^ || | +-- UNALIGNED POINTER ADDRESS: 0x20000001 || +---------------------- ALIGNED 32-BIT BOUNDARY: 0x20000000 || || Word 1 Address: 0x20000004 (Aligned 4-Byte Word Boundary) || +-------------------+-------------------+-------------------+-------------+ || | Byte 4 (Offs +4) | Byte 5 (Offs +5) | Byte 6 (Offs +6) | Byte 7 | || | payload_len[3] | crc[0] | crc[1] | Padding / | || | (byte 3 of u32) | (byte 0 of u16) | (byte 1 of u16) | Next Field | || +-------------------+-------------------+-------------------+-------------+ || ^ || +-- UNALIGNED CRC FIELD: 0x20000005 || || Result: 32-bit load (LDR) from 0x20000001 spans Word 0 AND Word 1. || - Cortex-M0/M0+: Hardware cannot split word loads -> Instant HardFault! || - Cortex-M3/M4/M7: Succeeds in Normal RAM; FAULTS if Device RAM or Trap. || |+-----------------------------------------------------------------------------+
On Cortex-M3/M4/M7 this often works out-of-the-box in Normal SRAM. On Cortex-M0/M0+ it always crashes if raw happens to reside at an address not divisible by 4. On Cortex-M3/M4/M7 it crashes if:
UNALIGN_TRP bit (bit 3) in the Configuration and Control Register (SCB->CCR) is set.LDMIA/STMIA or LDRD/STRD), which architecturally require word alignment regardless of core settings.Modern optimizing compilers inspect memcpy and struct assignments aggressively. When the copy size is small and fixed at compile time (such as sizeof(packet_t) == 7 or a 4-byte/8-byte block), GCC and Clang will often lower memcpy inline to:
LDR / STR for 32-bit wordsLDR / LDRH / LDRB sequences for non-multiple lengthsLDMIA / STMIA or LDRD / STRD for multi-word copiesVLDR / VSTR) on Cortex-M4F/M7FThese instructions have strict hardware alignment rules:
LDR/STR): Permitted on unaligned addresses only on ARMv7-M (Cortex-M3/M4/M7) when targeting Normal memory with CCR.UNALIGN_TRP = 0. On ARMv6-M (Cortex-M0/M0+), unaligned single-word loads always trigger a HardFault.LDM/STM, PUSH/POP, LDRD/STRD): Strictly require 4-byte natural alignment across all Cortex-M cores. An unaligned address will always fault, regardless of CCR trap settings.Optimization level behavior:
-O0: Calls standard C library memcpy (byte-by-byte or dynamically aligned loop) - safe on all Cortex-M cores, but higher call overhead.-O1 / -O2: Compilers assume unaligned hardware support by default on ARMv7-M (-munaligned-access). GCC inlines small copies using 32-bit LDR/STR words. This faults if raw is unaligned on Cortex-M0/M0+, on Cortex-M3/M4/M7 if UNALIGN_TRP = 1, or if pointers touch Device memory.-O3 / -Os: Aggressively inlines copies using LDM/STM or LDRD/STRD to maximize throughput or minimize code density. This strictly faults on any Cortex-M core if the address is not 4-byte aligned.-mno-unaligned-access: Forces the compiler to emit LDRB/STRB byte or halfword sequences for packed structs and unknown alignments - safe across all Cortex-M cores.When an unaligned fault occurs on ARMv7-M (Cortex-M3, Cortex-M4, Cortex-M7) or ARMv8-M Mainline (Cortex-M33, Cortex-M55, Cortex-M85), the processor pushes the exception stack frame (R0-R3, R12, LR, PC, xPSR) onto the active stack (MSP or PSP) and branches to the fault handler. The Configurable Fault Status Register (CFSR) located at 0xE000ED28 records the exact fault classification.
[!IMPORTANT] Architecture Distinction (ARMv6-M vs ARMv7-M/v8-M): Cortex-M0 and Cortex-M0+ (ARMv6-M) do not implement
SCB->CFSR,UFSR,BFSR, orMMFSR. On Cortex-M0/M0+, all faults vector directly toHardFault_Handler, and the only status register isSCB->HFSR(which does not report unaligned access details). On ARMv6-M, you must extract the stacked Program Counter (PC) from the stack frame and disassemble the faulting instruction to identify an unaligned access.
On ARMv7-M / ARMv8-M, the 32-bit CFSR register combines three individual fault status registers:
0xE000ED28): MemManage Fault Status Register0xE000ED29): BusFault Status Register0xE000ED2A): UsageFault Status Register+-----------------------------------------------------------------------------+| CONFIGURABLE FAULT STATUS REGISTER (SCB->CFSR: 0xE000ED28) |+=============================================================================+| || Bits [31:16]: UsageFault (UFSR) Bits [15:8]: BFSR Bits [7:0]: MMFSR || +--+--+--+--+--+--+--+--+--+--+--+--+------------------+------------------+ || |31|30|26|25|24|23|20|19|18|17|16| BusFault Status | MemManage Status | || | RESERVED|D |U | RES|N |I |I |U | Register | Register | || | |I |N | |O |N |N |N | (BFSR) | (MMFSR) | || | |V |A | |C |V |V |D | (Bits 15:8) | (Bits 7:0) | || | |0 |L | |P |P |S |E | | | || | | |I | | |C |T |F | | | || | | |G | | | |A |I | | | || | | |N | | | |T |N | | | || +--+--+--+--+--+--+--+--+--+--+--+--+------------------+------------------+ || | | | | || | | | +-- Bit 19: NOCP (FPU/Coprocessor Disabled) || | | +---------- Bit 24: UNALIGNED (SCB_CFSR_UNALIGNED_Msk) || | +------------- Bit 25: DIVBYZERO (Divide by Zero Trap) || +----------------------- UsageFault Status Register (UFSR, Bits 31:16) || |+-----------------------------------------------------------------------------+
Within the 16-bit UsageFault Status Register (UFSR):
CFSR bit 16): UNDEFINSTR - Execution of an undefined instructionCFSR bit 17): INVSTATE - Execution in an invalid EPSR state (e.g., Thumb bit cleared)CFSR bit 18): INVPC - Invalid EXC_RETURN value loaded to PCCFSR bit 19): NOCP - Coprocessor disabled or not present (e.g., FPU instruction without CPACR enabled)CFSR bit 24): UNALIGNED - Attempted unaligned memory access with trapping enabled or via LDM/STM/LDRD/STRDCFSR bit 25): DIVBYZERO - Divide by zero when CCR.DIV_0_TRP is enabled#include <stdint.h>/* CMSIS standard definitions:* SCB_CFSR_USGFAULTSR_Pos = 16* SCB_CFSR_UNALIGNED_Pos = 24* SCB_CFSR_UNALIGNED_Msk = (1UL << 24)* UFSR bit 8 = (1U << 8) = 0x0100*/__attribute__((naked)) void HardFault_Handler(void) {__asm volatile ("tst lr, #4 \n" /* Test EXC_RETURN bit 2: 0 = MSP, 1 = PSP */"ite eq \n""mrseq r0, msp \n" /* If equal, context saved on MSP */"mrsne r0, psp \n" /* If not equal, context saved on PSP */"ldr r1, =hard_fault_handler_c \n""bx r1 \n");}void hard_fault_handler_c(uint32_t *stacked) {/* Stack frame layout (basic 8-word frame):* stacked[0] = R0* stacked[1] = R1* stacked[2] = R2* stacked[3] = R3* stacked[4] = R12* stacked[5] = LR (Link Register before exception)* stacked[6] = PC (Program Counter at instruction that faulted!)* stacked[7] = xPSR*/uint32_t cfsr = SCB->CFSR;uint32_t ufsr = (cfsr >> 16) & 0xFFFFU;if (cfsr & (1UL << 24)) { /* SCB_CFSR_UNALIGNED_Msk (bit 8 of UFSR) */uint32_t fault_pc = stacked[6];/* UsageFault does NOT populate BFAR!* The faulting instruction address is fault_pc.* The unaligned data pointer must be decoded from the registers* (e.g., stacked[0] for R0, stacked[1] for R1) based on the instruction opcode.*/log_unaligned_fault(fault_pc, stacked);/* Write-1-to-clear the UNALIGNED status flag */SCB->CFSR = (1UL << 24);}while (1) {__asm volatile ("bkpt #0");}}
A frequent source of confusion is looking for the faulting memory address in SCB->BFAR (Bus Fault Address Register) or SCB->MMFAR (MemManage Fault Address Register).
[!WARNING] UsageFaults Do Not Populate BFAR or MMFAR: When an unaligned access triggers a UsageFault (
UFSR.UNALIGNED), the processor does not update BFAR or MMFAR. TheBFARVALIDbit in BFSR remains 0. If you inspectSCB->BFAR, it will contain either 0 or stale data from a previous BusFault.
+-----------------------------------------------------------------------------+| HARDWARE EXCEPTION STACK FRAME LAYOUT (MSP OR PSP) |+=============================================================================+| || Address Offset Pushed Register Contents Description || ----------------- ---------------------------------- ------------------ || SP + 0x1C (28) xPSR Program Status Reg || SP + 0x18 (24) Return Address (PC) FAULTING OPCODE PC || SP + 0x14 (20) Link Register (LR / R14) Caller Return Link || SP + 0x10 (16) Register R12 Scratch Register || SP + 0x0C (12) Register R3 Argument / Scratch || SP + 0x08 (8) Register R2 Argument / Scratch || SP + 0x04 (4) Register R1 Argument / Buffer || SP + 0x00 (0) Register R0 <--- Active SP Argument / Buffer || || * Note: UsageFault does NOT populate BFAR. Retrieve the faulting opcode || address directly from the stacked PC (SP + 0x18)! || |+-----------------------------------------------------------------------------+
The address of the offending instruction is preserved in stacked[6] (PC). To identify the exact memory address that caused the fault:
- Look up
fault_pcin your firmware.mapfile or disassembly (arm-none-eabi-objdump -d).- Inspect the base and offset registers referenced by the load/store instruction.
- Read the register values from
stacked[0]throughstacked[4](R0-R3, R12) or the active register set.
Key CFSR bits for unaligned access diagnosis:
CFSR bit 24 (UFSR bit 8, 0x0100): UNALIGNED - Unaligned load/store trapped or multi-register unaligned transfer attempted.SCB->SHCSR bit 18 (USGFAULTENA): If cleared (the reset default), any UsageFault automatically escalates to a HardFault (setting HFSR.FORCED bit 30). Set SCB->SHCSR |= (1UL << 18); to route unaligned traps directly to UsageFault_Handler.-mno-unaligned-accessThe most reliable system-wide fix is instructing the compiler not to assume hardware support for unaligned word transfers. This flag forces the code generator to lower structure accesses and inlined memory copies to byte-wise or halfword sequences whenever alignment is not guaranteed.
# GCC (arm-none-eabi-gcc) and Clang:-mno-unaligned-access# ARM Compiler 6 (armclang - LLVM-based):-mno-unaligned-access# ARM Compiler 5 (armcc - Legacy Keil):--no_unaligned_access# IAR Embedded Workbench for ARM (iccarm):--no_unaligned_access
[!NOTE] On Cortex-M0 and Cortex-M0+ (
-mcpu=cortex-m0), GCC and Clang default to strict alignment because the hardware inherently lacks unaligned access instructions. However, on Cortex-M3, M4, and M7, compilers default to-munaligned-access. Explicitly passing-mno-unaligned-accessensures identical, crash-proof behavior across all architectures.
Consider copying a 32-bit integer through an unaligned packed structure:
typedef struct __attribute__((packed)) {uint32_t val;} packed_u32_t;void copy_packed(packed_u32_t *dst, const packed_u32_t *src) {dst->val = src->val;}
Default compilation (-munaligned-access on ARMv7-M):
copy_packed:ldr r2, [r1] @ Emits single 32-bit load (LDR)str r2, [r0] @ Emits single 32-bit store (STR)bx lr @ FAULTS if r1 or r0 is unaligned and CCR.UNALIGN_TRP=1
Hardened compilation (-mno-unaligned-access):
copy_packed:ldrb r2, [r1] @ Load byte 0ldrb r3, [r1, #1] @ Load byte 1ldrb ip, [r1, #2] @ Load byte 2ldrb lr, [r1, #3] @ Load byte 3strb r2, [r0] @ Store byte 0strb r3, [r0, #1] @ Store byte 1strb ip, [r0, #2] @ Store byte 2strb lr, [r0, #3] @ Store byte 3bx lr @ 100% immune to unaligned faults on any core
Trade-offs: Code size increases slightly for packed accesses (4 byte instructions instead of 1 word instruction), with minor cycle overhead. Large calls to memcpy with non-constant lengths still invoke the C runtime library implementation.
On Cortex-M3/M4/M7, hardware unaligned access support applies exclusively to Normal memory. The ARM architecture specification strictly prohibits unaligned accesses to Device and Strongly-ordered memory regions. Any unaligned load or store targeting Device memory generates an immediate Alignment fault (UsageFault/HardFault), regardless of CCR.UNALIGN_TRP.
+-----------------------------------------------------------------------------+| ARMv7-M MEMORY ATTRIBUTE & ALIGNMENT RESOLUTION |+=============================================================================+| || Memory Access Request (e.g. LDR r0, [r1]) || | || v || Is target address 4-byte aligned? || | || +--------------------+--------------------+ || | YES | NO || v v || [ Normal Bus Transfer ] What is the Memory Region || Executes in single cycle Type configured in MPU? || | || +------------------------------+ || | | || v v || [ Normal Memory ] [ Device / Strongly-Ord ] || (SRAM / Flash) (Peripheral Registers) || | | || v v || Is CCR.UNALIGN_TRP == 1? ALWAYS FAULTS! || | Hardware bus prohibits || +----------+----------+ unaligned transactions || | NO | YES (Generates BusFault / || v v Alignment Error) || [ Hardware Emulation ] [ UsageFault Raised ] || Core splits access into SCB->CFSR bit 24 set || multiple bus cycles (Escalates to HardFault) || |+-----------------------------------------------------------------------------+
In many vendor-generated BSPs (including STM32CubeMX or early hardware startup code), memory regions are misconfigured:
If your SRAM is marked as Device memory, executing memcpy with an odd byte offset will instantly crash into a HardFault - even on a high-end Cortex-M7 with unaligned traps disabled.
#include "stm32f7xx_hal.h" /* Or equivalent CMSIS / HAL header */void MPU_Config(void) {MPU_Region_InitTypeDef MPU_InitStruct = {0};/* Ensure outstanding memory transactions complete before reconfiguring */__DMB();/* Disable the MPU */HAL_MPU_Disable();/* Region 0: Flash (Normal, Cacheable, Read-Only / Executable) */MPU_InitStruct.Enable = MPU_REGION_ENABLE;MPU_InitStruct.Number = MPU_REGION_NUMBER0;MPU_InitStruct.BaseAddress = 0x08000000U;MPU_InitStruct.Size = MPU_REGION_SIZE_1MB;MPU_InitStruct.SubRegionDisable = 0x00U;MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS;MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_ENABLE;MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE;MPU_InitStruct.IsCacheable = MPU_ACCESS_CACHEABLE;MPU_InitStruct.IsBufferable = MPU_ACCESS_BUFFERABLE;HAL_MPU_ConfigRegion(&MPU_InitStruct);/* Region 1: SRAM (NORMAL MEMORY - Outer & Inner Write-Back, Write-Allocate)* Setting TEX=001, C=1, B=1 marks RAM as Normal memory, enabling hardware unaligned access!*/MPU_InitStruct.Number = MPU_REGION_NUMBER1;MPU_InitStruct.BaseAddress = 0x20000000U;MPU_InitStruct.Size = MPU_REGION_SIZE_512KB;MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL1;MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS;MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_ENABLE;MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE;MPU_InitStruct.IsCacheable = MPU_ACCESS_CACHEABLE;MPU_InitStruct.IsBufferable = MPU_ACCESS_BUFFERABLE;HAL_MPU_ConfigRegion(&MPU_InitStruct);/* Region 2: Peripherals (DEVICE MEMORY - Unaligned access strictly prohibited by hardware) */MPU_InitStruct.Number = MPU_REGION_NUMBER2;MPU_InitStruct.BaseAddress = 0x40000000U;MPU_InitStruct.Size = MPU_REGION_SIZE_512MB;MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS;MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE;MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE;MPU_InitStruct.IsBufferable = MPU_ACCESS_BUFFERABLE; /* Shared Device: TEX=0, C=0, B=1 */HAL_MPU_ConfigRegion(&MPU_InitStruct);/* Enable MPU with default memory map for background privileged accesses */HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);/* Architectural memory barriers to ensure pipeline and bus use new MPU rules */__DSB();__ISB();}
Memory Attribute Rule:
TEX = 001, C = 1, B = 1 (or TEX = 000, C = 1, B = 1). Permits unaligned LDR/STR transfers when CCR.UNALIGN_TRP = 0.TEX = 000, C = 0, B = 1 (Device) or TEX = 000, C = 0, B = 0 (Strongly-ordered). Unaligned accesses always fault at the bus hardware level.When building portable firmware libraries or operating across mixed Cortex-M cores without relying on compiler flags, adopt explicit safe copying patterns.
Hardware registers residing in Device memory cannot be bulk-copied using memcpy or byte-by-byte loops, because many peripheral buses (such as APB/AHB on STM32) discard or corrupt partial-word accesses.
/* CORRECT: Read peripheral register with native 32-bit access,* then serialize safely into unaligned byte destination buffer.*/static inline void read_peripheral_fifo_unaligned(uint8_t *dst_ram,volatile const uint32_t *src_reg,size_t word_count) {for (size_t i = 0; i < word_count; i++) {uint32_t val = *src_reg; /* Native 32-bit aligned peripheral read */dst_ram[0] = (uint8_t)(val & 0xFFU);dst_ram[1] = (uint8_t)((val >> 8) & 0xFFU);dst_ram[2] = (uint8_t)((val >> 16) & 0xFFU);dst_ram[3] = (uint8_t)((val >> 24) & 0xFFU);dst_ram += 4;}}
safe_memcpy ImplementationAvoid compiler-inlined __builtin_memcpy macros that silently generate unaligned word instructions. Use a verified byte-safe function that falls back to 32-bit transfers only when both source and destination pointers are naturally aligned:
#include <stddef.h>#include <stdint.h>/*** @brief Copies bytes safely between memory regions, preventing Cortex-M unaligned faults.*/static inline void *safe_memcpy(void *dst, const void *src, size_t n) {uint8_t *d = (uint8_t *)dst;const uint8_t *s = (const uint8_t *)src;/* If both pointers are 4-byte aligned, transfer fast 32-bit words */if ((((uintptr_t)d | (uintptr_t)s) & 0x03U) == 0U) {uint32_t *d32 = (uint32_t *)d;const uint32_t *s32 = (const uint32_t *)s;size_t words = n / 4U;while (words--) {*d32++ = *s32++;}d = (uint8_t *)d32;s = (const uint8_t *)s32;n &= 0x03U;}/* Copy remaining bytes (or all bytes if pointers were unaligned) */while (n--) {*d++ = *s++;}return dst;}
Prevent alignment faults at compile time and link time by enforcing natural alignment on communication buffers:
#include <stddef.h>#include <stdint.h>#define BUFFER_ALIGNMENT 4U#define ALIGNED_BUF __attribute__((aligned(BUFFER_ALIGNMENT)))/* Hardware DMA and network buffers must always be word-aligned */ALIGNED_BUF static uint8_t rx_buffer[256];ALIGNED_BUF static uint8_t tx_buffer[256];typedef struct ALIGNED_BUF {uint32_t magic;uint32_t payload_len;uint16_t sequence_id;uint16_t crc16;uint8_t payload[]; /* C99 flexible array member */} telemetry_frame_t;/* Compile-time contract verification */_Static_assert(offsetof(telemetry_frame_t, payload_len) % 4U == 0U,"payload_len must reside on a 4-byte boundary");_Static_assert(sizeof(telemetry_frame_t) % 4U == 0U,"telemetry_frame_t header size must be a multiple of 4");
Taking the address of a packed struct member (e.g., &pkt->payload_len) triggers the compiler warning -Waddress-of-packed-member because dereferencing that pointer as uint32_t * creates an invalid unaligned pointer. Extract members using byte deserialization or explicit offset copying:
typedef struct __attribute__((packed)) {uint8_t cmd_type;uint32_t sequence; /* Offset 1: unaligned! */uint16_t data_len; /* Offset 5: unaligned! */} wire_packet_t;/* Portable, endian-safe, and alignment-immune field extractors */static inline uint32_t get_wire_sequence(const wire_packet_t *pkt) {const uint8_t *p = (const uint8_t *)&pkt->sequence;return (uint32_t)p[0] |((uint32_t)p[1] << 8) |((uint32_t)p[2] << 16) |((uint32_t)p[3] << 24);}static inline void set_wire_sequence(wire_packet_t *pkt, uint32_t seq) {uint8_t *p = (uint8_t *)&pkt->sequence;p[0] = (uint8_t)(seq & 0xFFU);p[1] = (uint8_t)((seq >> 8) & 0xFFU);p[2] = (uint8_t)((seq >> 16) & 0xFFU);p[3] = (uint8_t)((seq >> 24) & 0xFFU);}
Execute this test case on the target microcontroller to verify that copy routines operate flawlessly across odd byte boundaries:
#include <stdint.h>#include <string.h>#include <assert.h>void test_unaligned_safe_memcpy(void) {uint8_t raw_src[64];uint8_t raw_dst[64];/* Initialize source data pattern */for (size_t i = 0; i < sizeof(raw_src); i++) {raw_src[i] = (uint8_t)(i ^ 0x5AU);}memset(raw_dst, 0, sizeof(raw_dst));/* Test all combinations of misalignments (offsets 0 to 3) and copy lengths */for (size_t src_offset = 0; src_offset < 4; src_offset++) {for (size_t dst_offset = 0; dst_offset < 4; dst_offset++) {for (size_t len = 1; len <= 32; len++) {uint8_t *dst_ptr = &raw_dst[dst_offset];const uint8_t *src_ptr = &raw_src[src_offset];safe_memcpy(dst_ptr, src_ptr, len);assert(memcmp(dst_ptr, src_ptr, len) == 0);}}}}
Add static checks to your build pipeline to identify risky packed struct usage or missing compilation flags:
# Verify compiler flag presence in compile commandsgrep -- "-mno-unaligned-access" compile_commands.json || echo "WARNING: Flag missing!"# Flag unaligned pointer address conversionsgrep -rn "taking address of packed member" build.log# Ensure packed structs are not directly dereferenced with word castsgrep -rnE "\(uint32_t\s*\*\)\s*&" src/
#include <stdint.h>#ifdef DEBUG#define ASSERT_ALIGNED(ptr, align) \do { \if (((uintptr_t)(ptr) & ((align) - 1U)) != 0U) { \__asm volatile ("bkpt #1"); \} \} while (0)#else#define ASSERT_ALIGNED(ptr, align) ((void)0)#endifvoid handle_incoming_frame(const uint8_t *frame_buffer) {/* Verify 4-byte alignment before processing word transfers */ASSERT_ALIGNED(frame_buffer, 4U);}
/* ILLEGAL: Discards volatile qualifier; compiler may optimize away writes,* and memory-mapped hardware registers reject unaligned or byte-wide accesses.*/memcpy((void *)dst_peripheral_reg, (const void *)src_buffer, len);
Fix: Never use memcpy to write peripheral registers. Access registers through explicit volatile uint32_t * assignments with native bit widths.
/* DANGEROUS: Flash controllers often reject unaligned word loads */memcpy(ram_buffer, (const void *)0x08004001, 64);
Fix: Internal embedded Flash controllers on many microcontrollers (e.g., STM32, PIC32) mandate aligned 32-bit or 64-bit bus fetches. Performing unaligned reads from Flash can trigger a BusFault (BFSR.PRECISERR). Ensure all Flash addresses are 4-byte aligned or read through an aligned buffer.
/* DANGEROUS: Saves 3 padding bytes, but penalizes access cycles* and triggers faults on unaligned architectures.*/typedef struct __attribute__((packed)) {uint8_t type;uint32_t data; /* Offset 1: unaligned! */uint16_t flags; /* Offset 5: unaligned! */} msg_t;
Fix: Reorder structure members from largest to smallest alignment requirement (e.g., uint32_t, then uint16_t, then uint8_t). This naturally eliminates padding bytes without requiring __attribute__((packed)).
| Architecture / Scenario | Root Cause | Robust Solution |
|---|---|---|
| Cortex-M0 / Cortex-M0+ | No hardware unaligned support; ARMv6-M raises HardFault directly | Compile with -mno-unaligned-access |
| Cortex-M3 / M4 / M7 | Trapping enabled (CCR.UNALIGN_TRP=1) or multi-register (LDM/STM) | Clear UNALIGN_TRP or use -mno-unaligned-access |
| Device / Peripheral Space | ARM architecture prohibits unaligned access to Device memory | Map RAM as Normal memory in MPU; use native word accesses |
| Packed Wire Protocols | Pointer cast creates unaligned pointer (-Waddress-of-packed-member) | Deserialize via shift operators or safe_memcpy |
| DMA & Peripheral Buffers | Peripheral requires 32-bit or cache-line aligned RAM boundaries | Annotate with __attribute__((aligned(4))) |
Action items for firmware projects:
-mno-unaligned-access in CFLAGS (GCC/Clang/armclang) or --no_unaligned_access (IAR/armcc).TEX=001, C=1, B=1).safe_memcpy.__attribute__((aligned(4))).SCB_CFSR_UNALIGNED_Msk) decoding into your HardFault / UsageFault logging handler._Static_assert checks to validate buffer alignments and struct offsets.The next time your firmware halts in memcpy, you will know exactly how to inspect the stacked registers and eliminate unaligned faults permanently.
Quick Links
Legal Stuff





