Why strict aliasing is required in C?

Strict aliasing is a critical concept in C that helps prevent undefined behavior when accessing the same memory location through pointers of different types. Understanding why it's required helps write safer and more predictable C code.

What is Strict Aliasing?

Strict aliasing is a rule that states an object can only be accessed through pointers of compatible types. When this rule is violated, the behavior becomes undefined, leading to unpredictable results.

Example: Strict Aliasing Violation

Here's an example demonstrating what happens when strict aliasing rules are violated −

#include <stdio.h>

int temp = 5;

int my_function(double* var) {
    temp = 1;
    *var = 5.10;  /* This violates strict aliasing */
    return temp;
}

int main() {
    printf("Result: %d<br>", my_function((double*)&temp));
    return 0;
}
Result: 1717986918

The function was expected to return 1, but it returns a garbage value. This happens because we're accessing an int through a double* pointer, violating strict aliasing rules.

Why This Happens

The compiler assumes that pointers of different types don't point to the same memory location. When we cast &temp to double* and modify it, the compiler may optimize the code incorrectly, leading to undefined behavior.

Solution: Using restrict Keyword

The restrict keyword helps indicate that a pointer is the only way to access the memory it points to −

#include <stdio.h>

int safe_function(int* restrict var) {
    *var = 10;
    return *var;
}

int main() {
    int temp = 5;
    printf("Original: %d<br>", temp);
    printf("Modified: %d<br>", safe_function(&temp));
    return 0;
}
Original: 5
Modified: 10

Best Practices

  • Avoid casting pointers between incompatible types
  • Use restrict keyword when appropriate to help compiler optimization
  • Use union for legitimate type punning when necessary
  • Enable compiler warnings for strict aliasing violations

Conclusion

Strict aliasing rules prevent undefined behavior and enable better compiler optimizations. Following these rules ensures your C programs behave predictably and perform efficiently across different compilers and optimization levels.

Updated on: 2026-03-15T10:40:53+05:30

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements