Does &((struct name *)NULL -> b) cause undefined behaviour in C11?

前端 未结 6 1844
生来不讨喜
生来不讨喜 2020-11-27 04:53

Code sample:

struct name
{
    int a, b;
};

int main()
{
    &(((struct name *)NULL)->b);
}

Does this cause undefined behaviour? W

6条回答
  •  一向
    一向 (楼主)
    2020-11-27 05:12

    First, let's establish that we need a pointer to an object:

    6.5.2.3 Structure and union members

    4 A postfix expression followed by the -> operator and an identifier designates a member of a structure or union object. The value is that of the named member of the object to which the first expression points, and is an lvalue.96) If the first expression is a pointer to a qualified type, the result has the so-qualified version of the type of the designated member.

    Unfortunately, no null pointer ever points to an object.

    6.3.2.3 Pointers

    3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

    Result: Undefined Behavior.

    As a side-note, some other things to chew over:

    6.3.2.3 Pointers

    4 Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.
    5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.67)
    6 Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

    67) The mapping functions for converting a pointer to an integer or an integer to a pointer are intended to be consistent with the addressing structure of the execution environment.

    So even if the UB should happen to be benign this time, it might still result in some totally unexpected number.

提交回复
热议问题