Yes, casting between s1 and s2 in C with the strict aliasing rule in place can lead to undefined behavior (UB).
The strict aliasing rule in C is a rule that prevents accessing an object via a pointer of a type that is not compatible with the type of the object. This rule is intended to allow compilers to make certain optimizations.
In your example, you have two structs:
typedef struct { int i1; } s1;
typedef struct { int i2; } s2;
Even though s1 and s2 have the same layout (they both contain a single int), they are considered different types by the C standard. Therefore, accessing an object of type s1 through a pointer of type s2 (or vice versa) violates the strict aliasing rule, leading to undefined behavior.
Here’s an example that illustrates this:
#include <stdio.h>
typedef struct { int i1; } s1;
typedef struct { int i2; } s2;
int main() {
s1 obj1 = {42};
s2 *ptr = (s2 *)&obj1; // This cast violates the strict aliasing rule.
printf("%d\n", ptr->i2); // Undefined behavior
return 0;
}
In this code, the cast (s2 *)&obj1 is not allowed by the strict aliasing rule because s1 and s2 are different types. Accessing ptr->i2 after this cast leads to undefined behavior.
To avoid undefined behavior, you should ensure that you only access objects through pointers of compatible types. If you need to interpret the memory of one type as another, you should use a union or memcpy to ensure type safety:
#include <stdio.h>
#include <string.h>
typedef struct { int i1; } s1;
typedef struct { int i2; } s2;
int main() {
s1 obj1 = {42};
s2 obj2;
memcpy(&obj2, &obj1, sizeof(obj1)); // Safe way to copy the data.
printf("%d\n", obj2.i2); // Now this is well-defined.
return 0;
}
In this revised example, memcpy is used to copy the contents of obj1 to obj2, which is a safe operation and does not violate the strict aliasing rule.