Why does the NULL de-reference in this C snippet not cause undefined behaviour

六月ゝ 毕业季﹏ 提交于 2019-12-03 00:14:45

问题


I came across a piece of code where NULL is typecast to an structure pointer type (foo *) 0, and with that pointer de-referencing a member ((foo *)0)->m, and using address of that &(((foo *)0)->m)) and type casting it to integer to get the memory index of that member with in the structure.((unsigned int)(&(((foo *)0)->m))).

To my knowledge NULL pointer dereference should always result a segmentation fault in C. But I don't understand how NULL pointer can be de-referenced like this and still not result in a segmentation fault.

#include <stdio.h>
#define  MACRO(m) ((unsigned int)(&(((foo *)0)->m)))

typedef struct
{
int a;
int b;
int c;
int d;
}foo;

int main(void) {
    printf("\n  %d  ", MACRO(c));
    return 0;
}

回答1:


The C11 standard says in 6.5.3.2 Address and indirection operators:

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.

(Emphasis mine.) And the footnote says:

Thus, &*E is equivalent to E (even if E is a null pointer)

Interestingly, there's no exception for the -> operator. I don't know whether this was done deliberately or whether it is an oversight. So in a strict interpretation of the standard, I'd say that &(((foo *)0)->m) is undefined behavior. This doesn't mean that a program has to crash or that the compiler has to complain, though.

That said, it's completely reasonable to make the same exception when taking the address of the result of an -> operator, and that's what most compilers do.



来源:https://stackoverflow.com/questions/39409476/why-does-the-null-de-reference-in-this-c-snippet-not-cause-undefined-behaviour

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