HomeAbout UsContact Us

Fixing memcpy Hard Faults on Cortex-M: Unaligned Access Fix

By Jithin Tom
Published in Embedded C/C++
November 16, 2026
7 min read
Fixing memcpy Hard Faults on Cortex-M: Unaligned Access Fix

Table Of Contents

01
The Problem: When memcpy Becomes a Crash
02
Root Cause Analysis: Reading the CFSR Register
03
Solution 1: Compiler Flag -mno-unaligned-access
04
Solution 2: MPU Configuration - Mark RAM as Normal Memory
05
Solution 3: Safe Copy Patterns for Embedded C
06
Verification: Testing Your Fix
07
Common Pitfalls and Anti-Patterns
08
Summary
09
Related Reading
10
References
11
Frequently Asked Questions

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 |
| |
+-----------------------------------------------------------------------------+

The Problem: When memcpy Becomes a Crash

The Classic Scenario

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:

  • The UNALIGN_TRP bit (bit 3) in the Configuration and Control Register (SCB->CCR) is set.
  • The target memory region is mapped as Device or Strongly-ordered memory in the MPU.
  • The compiler optimizes the copy into multi-register load/store instructions (LDMIA/STMIA or LDRD/STRD), which architecturally require word alignment regardless of core settings.

Why the Compiler Emits Word Accesses

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:

  • A single LDR / STR for 32-bit words
  • Paired LDR / LDRH / LDRB sequences for non-multiple lengths
  • LDMIA / STMIA or LDRD / STRD for multi-word copies
  • Floating-point / vector instructions (VLDR / VSTR) on Cortex-M4F/M7F

These instructions have strict hardware alignment rules:

  • Single-word loads (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.
  • Multi-register transfers (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.

Root Cause Analysis: Reading the CFSR Register

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, or MMFSR. On Cortex-M0/M0+, all faults vector directly to HardFault_Handler, and the only status register is SCB->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.

CFSR Breakdown

On ARMv7-M / ARMv8-M, the 32-bit CFSR register combines three individual fault status registers:

  • MMFSR (bits 0-7, byte address 0xE000ED28): MemManage Fault Status Register
  • BFSR (bits 8-15, byte address 0xE000ED29): BusFault Status Register
  • UFSR (bits 16-31, halfword address 0xE000ED2A): 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):

  • Bit 0 (CFSR bit 16): UNDEFINSTR - Execution of an undefined instruction
  • Bit 1 (CFSR bit 17): INVSTATE - Execution in an invalid EPSR state (e.g., Thumb bit cleared)
  • Bit 2 (CFSR bit 18): INVPC - Invalid EXC_RETURN value loaded to PC
  • Bit 3 (CFSR bit 19): NOCP - Coprocessor disabled or not present (e.g., FPU instruction without CPACR enabled)
  • Bit 8 (CFSR bit 24): UNALIGNED - Attempted unaligned memory access with trapping enabled or via LDM/STM/LDRD/STRD
  • Bit 9 (CFSR 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");
}
}

Interpreting the Faulting Address

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. The BFARVALID bit in BFSR remains 0. If you inspect SCB->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:

  1. Look up fault_pc in your firmware .map file or disassembly (arm-none-eabi-objdump -d).
  2. Inspect the base and offset registers referenced by the load/store instruction.
  3. Read the register values from stacked[0] through stacked[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.

Solution 1: Compiler Flag -mno-unaligned-access

The 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.

Compiler Flags Comparison

# 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-access ensures identical, crash-proof behavior across all architectures.

Effect on Generated Code

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 0
ldrb r3, [r1, #1] @ Load byte 1
ldrb ip, [r1, #2] @ Load byte 2
ldrb lr, [r1, #3] @ Load byte 3
strb r2, [r0] @ Store byte 0
strb r3, [r0, #1] @ Store byte 1
strb ip, [r0, #2] @ Store byte 2
strb lr, [r0, #3] @ Store byte 3
bx 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.

Solution 2: MPU Configuration - Mark RAM as Normal Memory

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) |
| |
+-----------------------------------------------------------------------------+

The Peripheral and Memory Initialization Trap

In many vendor-generated BSPs (including STM32CubeMX or early hardware startup code), memory regions are misconfigured:

  • Internal Flash: Marked as Normal memory (Cacheable, Read-Only/Read-Write)
  • Internal SRAM: Inadvertently marked as Device or Strongly-ordered memory to avoid caching issues with DMA buffers

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.

Correct MPU Setup for Normal SRAM (PMSAv7)

#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:

  • SRAM (Normal Memory): Requires TEX = 001, C = 1, B = 1 (or TEX = 000, C = 1, B = 1). Permits unaligned LDR/STR transfers when CCR.UNALIGN_TRP = 0.
  • Peripherals (Device Memory): Configured as 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.

Solution 3: Safe Copy Patterns for Embedded C

When building portable firmware libraries or operating across mixed Cortex-M cores without relying on compiler flags, adopt explicit safe copying patterns.

Pattern 1: Peripheral Register Access (Native Word Reads)

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;
}
}

Pattern 2: Fault-Proof safe_memcpy Implementation

Avoid 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;
}

Pattern 3: Enforce Aligned Buffer Allocations

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");

Pattern 4: Safe Extraction from Packed Wire Protocols

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);
}

Verification: Testing Your Fix

Hardware Unit Test for Unaligned Memory Safety

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);
}
}
}
}

CI Static Analysis Checks

Add static checks to your build pipeline to identify risky packed struct usage or missing compilation flags:

# Verify compiler flag presence in compile commands
grep -- "-mno-unaligned-access" compile_commands.json || echo "WARNING: Flag missing!"
# Flag unaligned pointer address conversions
grep -rn "taking address of packed member" build.log
# Ensure packed structs are not directly dereferenced with word casts
grep -rnE "\(uint32_t\s*\*\)\s*&" src/

Runtime Alignment Assertion

#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)
#endif
void handle_incoming_frame(const uint8_t *frame_buffer) {
/* Verify 4-byte alignment before processing word transfers */
ASSERT_ALIGNED(frame_buffer, 4U);
}

Common Pitfalls and Anti-Patterns

Pitfall 1: Casting Away Volatile for memcpy

/* 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.

Pitfall 2: Assuming memcpy from Flash to RAM is Always Safe

/* 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.

Pitfall 3: Packing Structs for Memory Savings Without Realizing the Cost

/* 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)).

Summary

Architecture / ScenarioRoot CauseRobust Solution
Cortex-M0 / Cortex-M0+No hardware unaligned support; ARMv6-M raises HardFault directlyCompile with -mno-unaligned-access
Cortex-M3 / M4 / M7Trapping enabled (CCR.UNALIGN_TRP=1) or multi-register (LDM/STM)Clear UNALIGN_TRP or use -mno-unaligned-access
Device / Peripheral SpaceARM architecture prohibits unaligned access to Device memoryMap RAM as Normal memory in MPU; use native word accesses
Packed Wire ProtocolsPointer cast creates unaligned pointer (-Waddress-of-packed-member)Deserialize via shift operators or safe_memcpy
DMA & Peripheral BuffersPeripheral requires 32-bit or cache-line aligned RAM boundariesAnnotate with __attribute__((aligned(4)))

Action items for firmware projects:

  1. Pass -mno-unaligned-access in CFLAGS (GCC/Clang/armclang) or --no_unaligned_access (IAR/armcc).
  2. Configure your MPU to mark internal SRAM as Normal Cacheable memory (TEX=001, C=1, B=1).
  3. Replace unsafe macro copies with verified byte-safe functions like safe_memcpy.
  4. Align all communication buffers with __attribute__((aligned(4))).
  5. Incorporate CFSR bit 24 (SCB_CFSR_UNALIGNED_Msk) decoding into your HardFault / UsageFault logging handler.
  6. Add compile-time _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.

References

  1. ARM Limited. ARMv6-M Architecture Reference Manual. ARM DDI 0419E. Section A3.2.1 “Alignment support”.
  2. ARM Limited. ARMv7-M Architecture Reference Manual. ARM DDI 0403E. Section B1.5.7 “Alignment behavior” & Section B3.2.15 “Configurable Fault Status Register, CFSR”.
  3. ARM Limited. Cortex-M7 Processor Technical Reference Manual. ARM DDI 0489B. Section 2.3 “Memory system”.
  4. STMicroelectronics. STM32F7 Series Cortex-M7 Processor Programming Manual. PM0253. Section 2.1.3 “Alignment support”.
  5. Joseph Yiu. The Definitive Guide to ARM Cortex-M3 and Cortex-M4 Processors. 3rd ed. Newnes, 2014. Chapter 12 “Fault Handling”.
  6. ARM Limited. Arm Compiler for Embedded Reference Guide: -mno-unaligned-access. Arm DUI 1065.
  7. Free Software Foundation. Using the GNU Compiler Collection (GCC): ARM Options. https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html
  8. ARM Limited. Arm Cortex-M Fault Handling: Debugging HardFault and UsageFault exceptions. Application Note 209.
  9. Barr Group. Embedded C Coding Standard. Rule 8.2: “Avoid using memcpy for hardware register access” & Section 5 “Hardware-Independent Code”.
  10. MISRA C:2012. Guidelines for the use of the C language in critical systems. Rule 11.3 & Rule 11.4: “Pointer type conversions and alignment restrictions”.

Frequently Asked Questions

Why does memcpy cause a HardFault on Cortex-M0/M0+?

Cortex-M0 and Cortex-M0+ (ARMv6-M architecture) lack hardware support for unaligned memory accesses and do not possess configurable fault handlers (UsageFault, BusFault, or MemManage). When memcpy or compiler-generated word copies attempt a 16-bit or 32-bit load/store from an unaligned address, the core generates an immediate, unmaskable HardFault.

How do I identify if a HardFault is caused by unaligned access?

On ARMv7-M (Cortex-M3/M4/M7) and ARMv8-M Mainline (Cortex-M33), inspect the Configurable Fault Status Register (CFSR at 0xE000ED28). If bit 24 (bit 8 of the UFSR half-word, mask 0x0100) is set, an unaligned access occurred. Because UsageFault does not update BFAR/MMFAR, retrieve the faulting instruction address from the stacked PC. On ARMv6-M (Cortex-M0/M0+), CFSR is not implemented; you must inspect the stacked PC and disassemble the faulting instruction.

Can I just enable unaligned access support on Cortex-M3/M4/M7?

Cortex-M3/M4/M7 support unaligned single-register transfers (LDR/STR) in Normal memory by default, but they will still fault if the UNALIGN_TRP bit (CCR bit 3) is set, if the target is Device/Strongly-ordered memory, or if the compiler emits multi-register instructions (LDM/STM/LDRD/STRD), which architecturally always require alignment.

What is the safest way to copy potentially unaligned data in embedded C?

Use a byte-wise copy loop with uint8_t pointers, or compile with -mno-unaligned-access so the compiler automatically emits byte-safe load/store sequences. For memory-mapped peripheral registers, never use memcpy; read registers using native aligned 32-bit or 16-bit access widths, then transfer into RAM.

How do I prevent the compiler from generating unaligned word accesses?

Compile with -mno-unaligned-access (for GCC, Clang, and ARM Compiler 6 / armclang) or --no_unaligned_access (for legacy ARM Compiler 5 / armcc and IAR). This forces the compiler to use byte/halfword sequences instead of LDR/STR/LDM/STM for potentially unaligned pointers. Also use __attribute__((aligned(4))) on buffers shared with DMA/peripherals.

Tags

embedded-ccortex-mhard-faultmemcpyalignmentdebugging

Share


Previous Article
Fixing PREEMPT_RT Spinlock Sleeping Invalid Context
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing Embedded C Code That Breaks With -O2 Optimization
Fixing Embedded C Code That Breaks With -O2 Optimization
November 12, 2026
4 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media