Violating of strict-aliasing in C, even without any casting?

前端 未结 7 763
情深已故
情深已故 2021-01-31 07:02

How can *i and u.i print different numbers in this code, even though i is defined as int *i = &u.i;? I can only assuming

7条回答
  •  再見小時候
    2021-01-31 07:58

    C standard (i.e. C11, n1570), 6.5p7:

    An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

    • ...
    • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or a character type.

    The lvalue expressions of your pointers are not union types, thus this exception does not apply. The compiler is correct exploiting this undefined behaviour.

    Make the pointers' types pointers to the union type and dereference with the respective member. That should work:

    union {
        ...
    } u, *i, *p;
    

提交回复
热议问题