超过结构的一个元素来查看另一个元素是否合法? [英] Is it legal to overrun one element of a struct to view another?

查看:93
本文介绍了超过结构的一个元素来查看另一个元素是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下假设的示例代码:

Given the following contrived example code:

struct abc
{
    int x[5];
    int y[5];
};

void main()
{
    struct abc test;
    test.y[0] = 10;
    printf("%n", test.x[5]);
}

程序的输出为10。

虽然不是最好的编程实践,但这是工作。但是,这是一个编译器和平台的工件,还是这个法律代码? (即由C标准定义?)

While not the best programming practice, this does work. However, is this an artifact of the compiler and platform, or is this legal code? (i.e. defined by the C standard?)

即使结果不能保证为10,是否有一个实例,这将是非法到记忆我不拥有)?

Even if the result is not guaranteed to be 10, is there ever an instance where this would be "illegal" (i.e. writing to memory I do not "own")?

推荐答案

编辑:正如其他人指出的,这是不合法的,因为它导致未定义的行为。我已从我的答案中删除了这句话。

As pointed out by others, this is not legal, as it results in undefined behaviour. I've removed this sentence from my answer.

这有可能导致未定义的行为。你在struct abc中分配了一个10 ints long的内存块,所以索引到第5(6th)项将把你带到y [0],正如你在本特例中所说的。

This has the potential to result in undefined behaviour. You've allocated a memory chunk of 10 ints long in the struct abc, so indexing into the 5th (6th) item will take you to y[0] as you've noted in THIS specific case.

你可以遇到的问题是当C编译器以一种你不期望的方式打包结构。这称为数据打包或位对齐。当计算机想要从您的数据结构中访问内存时,它将尝试在整个结构的统一块中这样做。让我们使用一个例子:

Where you can run into problems is when the C compiler packs the structure in a way that you do not expect. This is called data packing or bit alignment. When the computer wants to access memory from your data structure, it will attempt to do so in uniform chunks for the entire structure. Let's use an example:

struct abc {
    int a;
    char b;
    int c;
};

你期望这个结构的大小是什么? int是32位,char是8位,因此总大小应该是32 + 8 + 32 = 72位。然而,你会发现在许多系统上,这个结构实际上是96位大小。原因是char b在结尾有一个额外的24位,以保持变量之间的标准偏移。

What do you expect the size of this struct to be? An int is 32 bits, and a char is 8 bits, so the total size should be 32 + 8 + 32 = 72 bits. However, you will find that on many systems, this structure is actually 96 bits in size. The reason is that char b gets bit packed on the end with an additional 24 bits to maintain a standard offset between variables.

当你声明一个结构时,这可能是非常混乱

This can be extremely confusing when you declare a structure in two different places, and one gets bit packed while the other does not due to compile time options or configuration.

查找位打包和数据对齐或位对齐以获得更多的信息。

Look up bit packing and data alignment or bit alignment for more information.

这篇关于超过结构的一个元素来查看另一个元素是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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