C/C++ nullptr dereference [duplicate]

别等时光非礼了梦想. 提交于 2019-12-11 02:04:07

问题


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.



来源:https://stackoverflow.com/questions/38615436/c-c-nullptr-dereference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!