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
