Section 4.23

Strict aliasing and effective type

Definition

Strict aliasing is the C rule that an object, a region of memory holding a value, may be read or written only through an expression whose type matches the object’s effective type, apart from a few listed exceptions; the main exception lets character types access any object byte by byte. An object’s declaration fixes its effective type. For storage from malloc, the way the program writes or copies a value can establish its effective type for later reads. Two pointers alias when they reach the same memory; the rule lets compilers assume that pointers to unrelated types do not.

The idea

An optimizing compiler wants to keep values in processor registers instead of reloading them from memory, but only if no store in between can have changed that memory. Take this C function:

int f(int *i, float *g) { *i = 1; *g = 0.0f; return *i; }

If g could point at the same 4 bytes as i, the final read must go to memory; if it cannot, the function may simply return 1. Without some rule, a compiler would have to assume that every store through any pointer may change every variable whose address was ever taken, and reload them all after each store.

C settles the question by type. An int object may be accessed only through an expression of type int or of a few closely related types, so a store through a float pointer cannot legally change it, and the compiler may return 1. The type of an object works as a promise about what its memory holds, and the compiler believes the promise. A program that breaks it gets no error message; it gets code optimized for a situation the program does not create.

Character types are the one open door: any object may be read or written byte by byte through char, signed char or unsigned char, which is how memcpy works. The door opens one way only. Bytes may be used to view an int, but an array §14.5 declared as bytes may not be viewed as an int.

How it works

Section 6.5 of C11, the 2011 edition of the C standard, states the rule; the phrase strict aliasing itself comes from compilers, which name the matching option -fstrict-aliasing. Two terms come first. An lvalue is an expression that designates an object, such as x, *p, a[i] or s.len, and its type is the type of the access: reading *p where p has type float * is a float access, whatever the memory holds. The effective type of an object is the type against which accesses are checked.

Paragraph 6 of section 6.5 decides the effective type:

  1. An object with a declared type, such as a variable or an array, has that type as its effective type, permanently.

  2. Allocated memory, from malloc, calloc or realloc, has no declared type. A store through an lvalue of a non-character type gives it that lvalue’s type, for the store and for later reads until the next store.

  3. A copy into allocated memory with memcpy or memmove, or byte by byte as an array of a character type, gives it the effective type of the source object, if the source has one.

  4. Any other access to allocated memory takes the lvalue’s own type as the effective type for that access.

Paragraph 7 then allows an access only through an lvalue of the same type as the effective type, ignoring qualifiers such as const and whether an integer type is signed or unsigned; through a structure or union that contains such a member; or through a character type. The exact list is given under Stated precisely. Every other access is undefined behavior §4.12: the standard places no requirement on what the program then does.

Compilers turn the rule into type-based alias analysis §3.18: two lvalues whose types may not access the same object are assumed not to overlap. GCC §12.17 (the GNU Compiler Collection, from GNU, a free-software project whose name stands for GNU’s Not Unix) applies it at the optimization levels -O2, -O3 and -Os. The option -fno-strict-aliasing switches the assumption off; the Linux kernel, for one, is built with it.

To inspect the bytes themselves, read them through unsigned char. To interpret them as a value of another type, copy them into an object of that type with memcpy, or in C use a union with a member of each type. Reading the resulting value also requires that the bytes form a valid representation of the target type. Footnote 95 of C11 says that the bytes are then reinterpreted as the new type, a practice called type punning.

Worked example

Two answers from one program. Call f with both pointers aimed at the same 4 bytes: int n; f(&n, (float *)&n);. The store through g now writes an object whose effective type is int through a float lvalue, which breaks the rule. Built without optimization, the function stores 1, then stores 0.0 as a float, whose IEEE 754 §4.49 single-precision form is 32 zero bits [271], then reads the int back from memory and returns 0. Built with GCC at -O2, it returns 1, because the compiler kept the stored 1 in a register.

Reading a packet field. A receiver holds a packet in static unsigned char rx[64];, and rx[0] to rx[3] hold 00 00 01 02, a 32-bit count in big-endian §4.21 order (most significant byte first).

For the constant length 4, GCC and Clang compile this memcpy into a single load wherever the processor permits misaligned loads, so the correct form is as fast as the cast.

Allocated memory changes type with each store. After float *p = malloc(4); *p = 1.5f; the effective type of the 4 bytes is float, and reading *(int *)p breaks the rule. A later store *(int *)p = 7; makes the effective type int, and reads through int are then allowed.

Stated precisely

Let OO be an object, let EE be its effective type for an access, and let LL be the type of the lvalue used for the access. C11 section 6.5 paragraph 7 permits the access only if LL is one of the following: a type compatible with EE, which for the integer and floating types used here means EE itself, possibly under another name made with typedef; a qualified version of such a type; the signed or unsigned type corresponding to EE or to a qualified version of EE; a structure or union type that includes one of these types among its members, directly or inside a nested member; or a character type. Any other access has undefined behavior. EE is the declared type of OO if OO has one; for allocated memory, EE follows the four rules of paragraph 6 listed above.

Section 7.24.2.1 defines memcpy as copying characters, so its reads and writes are character accesses, which every effective type permits. The rule restricts accesses, not conversions: converting an int pointer to a float pointer is allowed when the alignment §4.22 fits, and only a read or write through the converted pointer can break the rule.

Limits and common mistakes

Passing tests prove nothing. A violation often works without optimization and fails at -O2, after a compiler upgrade, or after an unrelated change lets the compiler inline a function. GCC’s -Wstrict-aliasing warning catches only some cases.

-fno-strict-aliasing is a compiler’s promise, not C. Under GCC and Clang it makes such accesses behave as plain memory accesses, at the price of some lost optimization. The code is still not portable C.

memcpy copies bytes; it does not convert them. It does not change byte order, does not check that the source holds enough bytes, and does not make the bytes a valid value of the target type. C allows some types to have byte patterns that represent no value, which C11 calls trap representations, and reading one is undefined behavior. Exact-width integer types such as uint32_t have none.

Union reading differs between C and C++. Reading a union member other than the one last written reinterprets the bytes in C; in C++ it is undefined behavior, and C++20 offers std::bit_cast instead.

The rule covers type only. Alignment, pointer provenance §4.24 (which object a pointer was derived from), bounds, object lifetime §4.1 and data races §9.3 are separate requirements. A memcpy from freed memory is still a use-after-free §4.6.

restrict is a different promise. The keyword restrict on a pointer is the programmer’s promise that, while the pointer is in use, an object modified through it is accessed through no other pointer, whatever the types involved.

Questions answered

Why is memcpy often safer than casting a byte buffer to an unrelated type?

Because memcpy reads the buffer as bytes, which C always allows, and writes into a real object of the target type, so every later read uses that object’s own type; a cast instead reads byte memory through a pointer of another type, which can break two C rules at once. First, the cast pointer may be misaligned for the new type, and converting to a misaligned pointer is undefined behavior, meaning the C standard places no requirement on the program. Second, if the buffer is a declared array of bytes, reading it as, for example, a uint32_t breaks the strict aliasing rule: the array’s effective type, the type against which C checks every access, is a character type, and the rule does not let an object of a character type be read as a uint32_t. An optimizing compiler may then reorder or drop the read, so the bug can appear only at higher optimization levels.

The destination of memcpy is a variable that the compiler has aligned, and compilers turn a small constant-length memcpy into one load where the processor permits, so the safe form usually costs nothing. It is often safer rather than always safe because it fixes only those two problems. The program must still check that the source holds enough bytes, convert the byte order that the data format specifies, and make sure that the copied bytes form a valid value of the target type.

Related entries: Alignment (§4.22), Endianness (§4.21), Pointer provenance (§4.24), Alias analysis (§3.18), Undefined behavior (UB) (§4.12), Compiler optimization (§3.39). Further reading: [78, 271].