When extending a padded struct, why can't extra fields be placed in the tail padding?

前端 未结 4 1932
礼貌的吻别
礼貌的吻别 2020-12-09 14:34

Let\'s consider the structs :

struct S1 {
    int a;
    char b;
};

struct S2 {
    struct S1 s;       /* struct needed to make this compile as C without ty         


        
4条回答
  •  不知归路
    2020-12-09 15:34

    Let's consider some code:

    struct S1 {
        int a;
        char b;
    };
    
    struct S2 {
        S1 s;
        char c;
    };
    

    Let's consider what would happen if sizeof(S1) == 8 and sizeof(S2) == 8.

    struct S2 s2;
    struct S1 *s1 = &(s2.s);
    memset(s1, 0, sizeof(*s1));
    

    You've now overwritten S2::c.


    For array alignment reasons, S2 also cannot have a size of 9, 10, or 11. So the next valid size is 12.

提交回复
热议问题