Does the following code violate strict aliasing?
int a = 0;
*((int *)((char *)&a)) = 1;
Why not? because we end up dereferencing the pointer of int a
using int *
which is legit
Why yes? because we cast the char *
to int *
and dereferencing it (the int *
), which seems as a strict aliasing violation
This code is valid. It is allowed to convert between two object pointer types and back provided there are not alignment issues, and converting to a char *
is explicitly allowed to access an objects representation (i.e. read the individual bytes).
Section 6.3.2.3p7 of the C standard states:
A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.
Since you covert from int *
to char *
then back to int *
, there are no strict aliasing violations here.