Course contentsShow
← C
Lesson 936 of 1,21913. Advanced CFree lesson

Strict aliasing rule violations

Strict aliasing rule violations

What you'll learn: How to avoid the subtle bugs that occur when you tell the compiler two pointers point to different things, but they actually point to the same memory.

The Compiler’s Assumption

Imagine you are a chef. If I tell you that the salt is in the blue jar and the sugar is in the red jar, you assume that changing the salt won't affect the sugar. You can work faster because you don't have to double-check the red jar every time you touch the blue one.

In C, the Strict Aliasing Rule is that same assumption for the compiler. It states that two pointers of different types (like an int* and a float*) will never point to the same memory address. This allows the compiler to optimize your code aggressively by rearranging instructions, assuming that writing to an integer won't "magically" change a nearby float.

Breaking the Promise

When you use a pointer cast to treat an object of one type as another, you are "aliasing" that memory. If you violate the strict aliasing rule, the compiler might use a "stale" value from a register instead of re-reading memory, leading to values that seem to change (or fail to change) at random.

#include <stdio.h>

void mystery_function(float *f, int *i) {
    *f = 1.0; 
    *i = 2;    // If f and i point to the same memory, this line 
               // should overwrite the float value.
    
    // Violation: The compiler assumes *f is still 1.0 because 
    // an int pointer should never alias a float pointer.
    printf("Float value: %f\n", *f);
}

int main() {
    float data = 0.0;
    // We force the violation by casting a float pointer to an int pointer
    mystery_function(&data, (int *)&data);
    return 0;
}

On a modern compiler with optimizations turned on (-O2 or -O3), the code above might print 1.000000 instead of the integer bit-pattern you expected. The compiler "remembered" that *f was 1.0 and decided it didn't need to look at the memory again after the integer assignment.

Staying Safe

The "Dark Side" of this rule is that your code might work perfectly for years until you turn on a specific optimization flag. To stay safe, never use type-punning through pointer casting. If you truly need to view the same bytes as two different types, use a union or memcpy, which are specifically designed to tell the compiler: "Heads up, this memory is being shared!"

Key takeaway

Strict aliasing allows the compiler to optimize code by assuming different pointer types don't overlap; breaking this rule via pointer casting leads to unpredictable, "ghostly" bugs.