C/C++ nullptr dereference [duplicate]

2019-07-09 00:36发布

问题:

This question already has an answer here:

  • Is there a platform or situation where dereferencing (but not using) a null pointer to make a null reference will behave badly? 6 answers

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++.

回答1:

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.


回答2:

If it is also an undefined behavior, how does offsetof work?

Prefer using the standard offsetof macro. Home-grown versions result in compiler warnings. Moreover:

offsetof is required to work as specified above, even if unary operator& is overloaded for any of the types involved. This cannot be implemented in standard C++ and requires compiler support.

offsetof is a built-in function in gcc.



标签: c++ c null nullptr