Is it OK to access past the size of a structure via member address, with enough space allocated?

前端 未结 3 733
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 04:25

Specifically, is the following code, the line below the marker, OK?

struct S{
    int a;
};

#include 

int main(){
    struct S *p;
    p =          


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 05:21

    C standard guarantees that
    §6.7.2.1/15:

    [...] A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

    &(p->a) is equivalent to (int *)p. &(p->a) + 1 will be address of the element of the second struct. In this case, only one element is there, there will not be any padding in the structure so this will work but where there will be padding this code will break and leads to undefined behaviour.

提交回复
热议问题