gcc如何计算结构所需的空间? [英] How does gcc calculate the required space for a structure?
问题描述
struct {
整数a;
struct c b;
...
}
一般gcc如何计算所需的空间?这里有谁曾经偷看到内部?
我没有偷看内部,但它很漂亮清楚,任何理智的编译器都会以完全相同的方式来完成。流程如下:
- 从大小0开始。
- 对于每个元素,到该元素的下一个对齐倍数,然后添加该元素的大小。
- 最后,将所有成员的对齐的最小公倍数进行舍入。 >
下面是一个例子(假设 int
是4个字节并且有4个字节对齐):
struct foo {
char a;
int b;
char c;
};
- 大小最初为0。 li>回到
char
(1);大小仍为0. - 添加大小
char
(1);大小现在为1。 - 轮到
int
(4);大小现在是4。 - 添加大小
int
(4);大小现在为8。
- 轮到
char
(1);大小仍然是8。
- 添加大小
char
(1);大小现在为9。
- Round to lcm(1,4)(4);大小现在为12。
- 轮到
编辑:要解决为什么最后一步是必要的,现在声明 struct foo myfoo [2];
并考虑& myfoo [1] .b
,它比 myfoo
开头的13个字节和& myfoo [0] .b
。这意味着 myfoo [0] .b
和 myfoo [1] .b
不可能与它们对齐需要对齐(4)。
struct {
integer a;
struct c b;
...
}
In general how does gcc calculate the required space? Is there anyone here who has ever peeked into the internals?
I have not "peeked at the internals", but it's pretty clear, and any sane compiler will do it exactly the same way. The process goes like:
- Begin with size 0.
- For each element, round size up to the next multiple of the alignment for that element, then add the size of that element.
- Finally, round size up to the least common multiple of the alignments of all members.
Here's an example (assume int
is 4 bytes and has 4 byte alignment):
struct foo {
char a;
int b;
char c;
};
- Size is initially 0.
- Round to alignment of
char
(1); size is still 0. - Add size of
char
(1); size is now 1. - Round to alignment of
int
(4); size is now 4. - Add size of
int
(4); size is now 8. - Round to alignment of
char
(1); size is still 8. - Add size of
char
(1); size is now 9. - Round to lcm(1,4) (4); size is now 12.
Edit: To address why the last step is necessary, suppose instead the size were just 9, not 12. Now declare struct foo myfoo[2];
and consider &myfoo[1].b
, which is 13 bytes past the beginning of myfoo
and 9 bytes past &myfoo[0].b
. This means it's impossible for both myfoo[0].b
and myfoo[1].b
to be aligned to their required alignment (4).
这篇关于gcc如何计算结构所需的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!