是“结构黑客"吗?技术上未定义的行为? [英] Is the "struct hack" technically undefined behavior?

查看:34
本文介绍了是“结构黑客"吗?技术上未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What I am asking about is the well known "last member of a struct has variable length" trick. It goes something like this:

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

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

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

Because of the way that the struct is laid out in memory, we are able to overlay the struct over a larger than necessary block and treat the last member as if it were larger than the 1 char specified.

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

So the question is: Is this technique technically undefined behavior?. I would expect that it is, but was curious what the standard says about this.

PS:我知道 C99 对此的方法,我希望答案特别适用于上面列出的技巧版本.

PS: I am aware of the C99 approach to this, I would like the answers to stick specifically to the version of the trick as listed above.

推荐答案

作为 C 常见问题解答 说:

不清楚它是合法的还是可移植的,但它很受欢迎.

It's not clear if it's legal or portable, but it is rather popular.

和:

... 官方解释认为它并不严格符合 C 标准,尽管它似乎在所有已知的实现下都可以工作.(仔细检查数组边界的编译器可能会发出警告.)

... an official interpretation has deemed that it is not strictly conforming with the C Standard, although it does seem to work under all known implementations. (Compilers which check array bounds carefully might issue warnings.)

严格符合"位背后的基本原理在规范中,J.2 未定义行为部分,其中包括未定义行为列表:

The rationale behind the 'strictly conforming' bit is in the spec, section J.2 Undefined behavior, which includes in the list of undefined behavior:

  • 数组下标超出范围,即使对象显然可以用给定的下标访问(如左值表达式 a[1][7] 给定声明 int a[4][5]) (6.5.6).
  • An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

6.5.6 加法运算符的第 8 段再次提到超出定义的数组边界的访问是未定义的:

Paragraph 8 of Section 6.5.6 Additive operators has another mention that access beyond defined array bounds is undefined:

如果指针操作数和结果都指向同一个数组对象的元素,或者超过数组对象最后一个元素,则求值不会产生溢出;否则,行为未定义.

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

这篇关于是“结构黑客"吗?技术上未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆