为什么内存对齐会在结构中发生变化?
在前一个问题中 ,我了解到当具有8字节对齐的结构嵌入到具有4字节对齐的另一个结构中时,在8字节对齐结构之前需要填充。
了解。
至少我以为我明白了。
VS 2012文档说:
对于结构,联合和数组,对齐要求是其成员的最大对齐要求。
所以,如果我有这样的结构:
typedef struct s_inner { unsigned long ul1; double dbl1; fourth_struct s4; unsigned long ul2; int i1; } t_inner;
我希望这个结构的所有成员都是8字节对齐的,因为double
是8字节对齐的。
但我的记忆转储告诉我这个:
t_inner
从地址1B8
开始:
-
1B8
:unsigned long
1B8
被填充,因为结构是8字节对齐的 -
1C0
:double
1C0
消耗8个字节 -
1C8
:fourth_struct
如下, 它具有4字节对齐
到目前为止,一切都如预期。 但是现在t_inner
内部的对齐开关 :在地址1E8
,我希望在这里只找到unsigned long
int
,填充4个字节,以便后面的int
也在8个字节上对齐。 但似乎对齐现在已经改变,因为unsigned long
整数不携带填充字节。 相反,以下int
以4字节对齐方式放置。
为什么对齐开关在t_inner
? 这里适用哪条规则?
我希望这个结构的所有成员都是8字节对齐的,因为double是8字节>对齐的。
好吧,不。 每个类型在结构内部都有自己的对齐方式, 结构本身的对齐方式是其内容的最大对齐方式。
aligned. typedef struct s_inner { unsigned long ul1; // 4-aligned double dbl1; // 8-aligned (need 4 padding before this) fourth_struct s4; // 4 aligned size 32 unsigned long ul2; // 4 aligned (no padding) int i1; // 4 aligned (no padding) // no padding needed as struct is a multiple of 8 bytes } t_inner;
由于双重结构,结构本身已对齐8。