Aliasing
Aliasing in programming occurs when multiple identifiers (variables, pointers, references) refer to the same memory location or object. E.g., pointer aliasing refers to two pointers pointing to the same memory address.
Strict Aliasing
The strict aliasing rule in C and C++ governs how pointers of different types can reference the same memory location. Following this rule can enable the compiler to perform aggressive optimizations.
The C standard specifies that it is illegal to access the same memory location using pointers of different types. Specifically, it can only be accessed through
- A pointer of the same type as what was used to create the object
- A pointer to a compatible type (like char*)
- A pointer to a signed/unsigned variant of the type
- A few other specific exceptions
Following code breaks strict aliasing because an int*
accesses memory that was
allocated as a float
:
float f = 1.0f; int* p = (int*)&f; // Violates strict aliasing *p = 0x3f800000; // Undefined behavior
Breaking strict aliasing can lead to unexpected behavior & bugs or code that works with one compiler but fails with another.
To avoid strict aliasing violations:
- Use proper type punning through unions
- Use
memcpy()
for type conversions - Enable compiler warnings with
-fstrict-aliasing
and-Wstrict-aliasing
- Use
-fno-strict-aliasing
flag if necessary (disables optimization)
restrict
Keyword in C
restrict
is a type qualifier in C for pointers. It hints to the compiler that
for the pointer lifetime, no other pointer will be used to access the object to
which it points (helping optimization efforts). If pointer aliasing still
occurs, it will result in undefined behavior.