代码之家  ›  专栏  ›  技术社区  ›  Evan Teran

“结构黑客”在技术上是未定义的行为吗?

  •  109
  • Evan Teran  · 技术社区  · 14 年前

    我要问的是著名的“结构的最后一个成员具有可变长度”技巧。就像这样:

    struct T {
        int len;
        char s[1];
    };
    
    struct T *p = malloc(sizeof(struct T) + 100);
    p->len = 100;
    strcpy(p->s, "hello world");
    

    由于结构在内存中的布局方式,我们可以将结构覆盖在一个大于必需的块上,并将最后一个成员视为大于 1 char 明确规定。

    所以问题是: 这项技术在技术上是未定义的行为吗? . 我想是的,但我很好奇标准怎么说。

    附言:我知道C99的方法,我希望答案特别坚持以上列出的技巧版本。

    8 回复  |  直到 12 年前
        1
  •  51
  •   Carl Norum    14 年前

    C FAQ

    • a[1][7] int a[4][5]

        2
  •  34
  •   Jerry Coffin    14 年前

        4
  •  11
  •   Chuck    14 年前

    char foo[] char

        5
  •  7
  •   R.. GitHub STOP HELPING ICE    14 年前

    p->s (char *)p + offsetof(struct T, s) char -> malloc char *

    p->s[0] p->s[1] p->s[3]

    1 [1] s[sizeof struct that_other_struct]; p->s[i] i<sizeof struct that_other_struct i>=sizeof struct that_other_struct

    struct T s[0]

        6
  •  7
  •   AnT stands with Russia    14 年前

    p->s[0] p->s[1]

        7
  •  3
  •   Bernhard R. Link    12 年前

        8
  •  1
  •   supercat    14 年前

    typedef struct {
      int len;
      char dat[];
    };

    typedef struct {
      int whatever;
      char dat[1];
    } MY_STRUCT;

    #define LARGEST_DAT_SIZE 0xF000
    typedef struct {
      int whatever;
      char dat[LARGEST_DAT_SIZE];
    } MY_STRUCT;