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

问题描述

我要问的是著名的struct的最后一个成员具有可变长度的把戏。它是这样的:

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.

推荐答案

由于说:

目前还不清楚,如果是合法的或便携式的,但它是相当受欢迎的。

...官方间pretation已经认定它没有严格遵守C标准一致,虽然它似乎在所有已知的实施工作。 (其中仔细检查数组边界的编译器可能会发出警告。)

背后的严格符合位的基本原理是在规范中,部分的 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:


      
  • 数组下标超出范围,即使对象是与给定的下标显然是可访问的(如在左值前pression A [1] [7] 给出的声明 int类型的[4] [5] )(6.5.6)。

  •   

节第8 6.5.6加法运算符有超出定义数组边界访问未定义再次提及:

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

如果这两个指针操作数和结果指向相同的数组对象,或者一个过去的数组对象的最后一个元素的元素,该评估也不得产生溢出;否则,行为是不确定的。

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

08-11 11:14