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

前端 未结 3 741
没有蜡笔的小新
没有蜡笔的小新 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:18

    This is undefined behavior, as you are accessing something that is not an array (int a within struct S) as an array, and out of bounds at that.

    The correct way to achieve what you want, is to use an array without a size as the last struct member:

    #include 
    
    typedef struct S {
        int foo;    //avoid flexible array being the only member
        int a[];
    } S;
    
    int main(){
        S *p = malloc(sizeof(*p) + 2*sizeof(int));
        p->a[0] = 0;
        p->a[1] = 42;    //Perfectly legal.
    }
    

提交回复
热议问题