</>EmbeddedInterview

What is strict aliasing?

HardPointers & Memory

Short answer: The strict aliasing rule says that an object may only be accessed through an expression of its own type (or a compatible type, its signed/unsigned variant, a qualified version, an aggregate or union containing it), or through a character type (char, unsigned char). The compiler uses this rule to assume that pointers to different types do not point to the same memory, so it can keep values in registers and reorder loads and stores. Breaking the rule is undefined behaviour.

#include <stdint.h>
#include <string.h>

uint32_t float_bits_bad(float f)
{
    return *(uint32_t *)&f;               /* UB: accessing a float through a uint32_t lvalue */
}

uint32_t float_bits_ok(float f)
{
    uint32_t u;
    memcpy(&u, &f, sizeof u);             /* defined; compiles to a single register move */
    return u;
}

How it breaks code in practice

int foo(int *i, float *f)
{
    *i = 1;
    *f = 2.0f;           /* compiler assumes f cannot point to the same object as i */
    return *i;           /* so it returns 1 without reloading, even if i and f alias */
}

Code like this often works at -O0 and silently changes behaviour at -O2.

Allowed ways to reinterpret bytes

  • memcpy into an object of the target type (the standard, recommended way; free after optimisation).
  • Reading through unsigned char * / uint8_t * (character types may alias anything).
  • A union (allowed in C; undefined in C++, where std::bit_cast in C++20 is the tool).

Embedded situations where it appears

  • Casting a received uint8_t buffer to a struct pointer (struct hdr *h = (struct hdr *)buf;), which is also an alignment risk. Copy into a struct with memcpy, or parse field by field.
  • Treating a uint32_t array as float samples.
  • Checksums computed by reading a struct as uint32_t words.

Escape hatch: -fno-strict-aliasing disables the optimisation; the Linux kernel and many embedded projects build with it. That makes such code work with GCC, but it is still non-portable C and gives up some optimisation, so prefer memcpy in new code. GCC's -Wstrict-aliasing catches some violations.