liveBook · Manning

Unaligned access

As explained in Embedded Software with Rust

An unaligned access is a processor memory access whose address does not satisfy the alignment required by the accessed value or instruction.

An unaligned access uses an address that does not meet the accessed value’s alignment requirement. In embedded Rust, packed layouts can place 16-bit or 32-bit fields at such addresses. This can require extra byte-wide accesses, slow execution, increase energy use, or trigger a HardFault, depending on the processor. section 5.4.3

use core::mem::{size_of, align_of};

/// A minimal two-field struct used to illustrate the effect of `#[repr(packed)]`.
/// This does not model any real hardware peripheral.
#[repr(C, packed)]
struct PackedExample {
    field16: u16,  // naturally 2-byte aligned
    field8: u8,    // naturally 1-byte aligned
}

fn main() {
    dbg!(size_of::<PackedExample>());  // 3 bytes: no padding inserted
    dbg!(align_of::<PackedExample>()); // 1 byte: the whole struct is byte-aligned
}

This host-side example shows how a packed struct can be three bytes in size yet only one-byte aligned, leaving its u16 field potentially unaligned. section 5.4.3

Avoid packed structs for memory-mapped register overlays. Stack pointers and data sections also need appropriate alignment: an 8-byte boundary supports 64-bit values, while misalignment can cause faults or unpredictable corruption. A linker script can enforce section alignment with ALIGN(8). section 5.4.3 section 4.1.3

How Embedded Software with Rust covers it

How deep it goes
Traces packed field alignment to extra accesses, performance costs, or faults, and identifies linker alignment needs.
Examples
Uses a packed two-field struct and explains stack and data-section alignment for 64-bit values.
What you can do after
Apply alignment constraints by avoiding packed MMIO overlays and aligning stack and data sections.
How it connects
Connects memory alignment with packed structs, memory-mapped I/O, linker scripts, the Arm ABI, and HardFaults.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.