Search code examples
c++cnullnullptr

C/C++ nullptr dereference


Since de-referencing nullptr (NULL) is an undefined behavior both in C and C++, I am wondering if expression &(*ptr) is a valid one if ptr is nullptr (NULL).

If it is also an undefined behavior, how does OFFSETOF macro in the linked answer work?

I always thought that ptr->field is a shorthand for (*ptr).field

I think the answer to my question is similar in C and C++.


Solution

  • TL;DR &(*(char*)0) is well defined.

    The C++ standard doesn't say that indirection of null pointer by itself has UB. Current standard draft, [expr.unary.op]

    1. The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T”, the type of the result is “T”. [snip]

    2. The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. [snip]

    There is no UB unless the lvalue of the indirection expression is converted to an rvalue.


    The C standard is much more explicit. C11 standard draft §6.5.3.2

    1. The unary & operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type". If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue. Similarly, if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator. Otherwise, the result is a pointer to the object or function designated by its operand.