What happens on an unaligned memory access, and how do you avoid it?
0 upvotes
Practice with AISoon
An unaligned access occurs when a multi-byte value is read from or written to an address that is not a multiple of its size (e.g., reading a uint32_t from address 0x03 instead of 0x04). The behavior depends on the architecture:
- Cortex-M0/M0+: generates a HardFault (crash). No recovery.
- Cortex-M3/M4/M7: handles it in hardware but with a performance penalty (extra bus cycles). Some accesses to certain memory regions still fault.
- x86: always handles it, with a small performance cost.
Common causes: casting a uint8_t* buffer to a uint32_t* to "read 4 bytes at once," packed structs, and deserializing network data by casting. The safe approach is memcpy() — the compiler optimizes it to an aligned load when possible, and handles unaligned cases correctly on all architectures.
Source: C / C++ Concepts Q&A
