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

前端 未结 6 1848
生来不讨喜
生来不讨喜 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:09

    No. Let's take this apart:

    &(((struct name *)NULL)->b);
    

    is the same as:

    struct name * ptr = NULL;
    &(ptr->b);
    

    The first line is obviously valid and well defined.

    In the second line, we calculate the address of a field relative to the address 0x0 which is perfectly legal as well. The Amiga, for example, had the pointer to the kernel in the address 0x4. So you could use a method like this to call kernel functions.

    In fact, the same approach is used on the C macro offsetof (wikipedia):

    #define offsetof(st, m) ((size_t)(&((st *)0)->m))
    

    So the confusion here revolves around the fact that NULL pointers are scary. But from a compiler and standard point of view, the expression is legal in C (C++ is a different beast since you can overload the & operator).

提交回复
热议问题