

On a Cortex-M3, the STR instruction accepts unaligned addresses.įor Cortex-M0, M0+, and M1, the Armv6-M Architecture Reference Manual informs us: A3.2.1 Alignment behavior On a Cortex-M0, the STR instruction used by set_data requires an aligned address. With a Cortex-M3, the same function call works fine. With a Cortex-M0, the result of set_data is a UsageFault exception. With the cast, we have tried to "fool" the compiler by saying that the uint8_t byte pointer &network_data really is an aligned uint32_t pointer, which is not true. Now, using the resulting data_p pointer gives undefined behavior.įor example, calling our set_data function with data_p results in undefined behavior: set_data(data_p, 1200) If we refer to an "odd" byte in our byte array and convert it to uint32_t with a cast, the behavior is undefined, because the resulting pointer is not correctly aligned for the pointed-to type: data_p = (uint32_t*) &network_data

Now, assume that we have a byte array, like this: uint8_t network_data = Fooling the compiler (If not, the behavior would be undefined.) With the following function definition, we tell the compiler that out_p is a pointer to an aligned uint32_t variable: void set_data(uint32_t *out_p, uint32_t val) This is a pointer to uint32_t: uint32_t *data_p īecause the 32-bit data type uint32_t has an alignment requirement, we know that the uint32_t pointer is correctly aligned. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined”. “A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type.

DiscussionĪccording to the C language standard ISO/IEC 9899: This Technical Note shows how to inform the compiler about the unaligned data, and thereby avoid trouble. Accessing the unaligned data in a safe and portable way can be tricky-the result can depend on the CPU architecture, the compiler optimization level, or even which memory region you are working with. Perhaps the data is in a buffer received from a network or serial link. Sometimes you want to access unaligned data.
