Please consider the following code:
typedef struct {
int type;
} object_t;
typedef struct {
object_t object;
int age;
} person_t;
int age(object_t *o
Strict aliasing rule is about two pointers of different types referencing the same location in memory (ISO/IEC9899/TC2). Although your example reinterprets the address of object_t object
as an address of person_t
, it does not reference memory location inside object_t
through the reinterpreted pointer, because age
is located past the boundary of object_t
. Since memory locations referenced through pointers are not the same, I'd say that it is not in violation of the strict aliasing rule. FWIW, gcc -fstrict-aliasing -Wstrict-aliasing=2 -O3 -std=c99
seems to agree with that assessment, and does not produce a warning.
This is not enough to decide that it's legal code, though: your example makes an assumption that the address of a nested structure is the same as that of its outer structure. Incidentally, this is a safe assumption to make according to the C99 standard:
6.7.2.1-13. A pointer to a structure object, suitably converted, points to its initial member
The two considerations above make me think that your code is legal.