相关疑难解决方法(0)

"struct hack"在技术上是不确定的行为吗?

我要问的是众所周知的"结构的最后一个成员有可变长度"的技巧.它是这样的:

struct T {
    int len;
    char s[1];
};

struct T *p = malloc(sizeof(struct T) + 100);
p->len = 100;
strcpy(p->s, "hello world");
Run Code Online (Sandbox Code Playgroud)

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

所以问题是:这种技术在技术上是不确定的行为吗?.我希望它是,但很好奇标准对此有何看法.

PS:我知道C99的方法,我希望答案专门针对上面列出的技巧版本.

c c89 undefined-behavior

109
推荐指数
7
解决办法
9414
查看次数

标签 统计

c ×1

c89 ×1

undefined-behavior ×1