混乱的结构成员对齐 [英] Confusion in Structure Member Alignment
问题描述
typedef struct structc_tag
{
char c;
double d;
int s;
} structc_t;
我在博客中读到,这将需要24字节数据:
I read in a blog that this will take 24 bytes of data:
的sizeof(char)的+ 7字节填充+的sizeof(双)+的sizeof(INT)+ 4字节填充= 1 + 7 + 8 + 4 + 4 = 24个字节。
sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) + 4 byte padding = 1 + 7 + 8 + 4 + 4 = 24 bytes.
我的问题是,为什么7字节填充,我们为什么不能用填充的3字节还有,利用接下来的8个字节双?什么是需要最后4个字节?
My question is why the 7 byte padding, why can't we use 3bytes of padding there and utilise next 8 bytes for double? And what is the need for last 4 bytes?
推荐答案
您需要考虑会发生什么,如果你分配这些结构数组与的malloc()
:
You need to consider what the happens if you allocate an array of these structures with malloc()
:
structc_t *p = malloc(2 * sizeof *p);
考虑一个平台,在这里的sizeof(双)== 8
,的sizeof(int)的== 4
和所需对准双击
是8 的malloc()
总是返回用于存储任何的C类型正确对齐的地址 - 所以在这种情况下, A
将是8字节对齐。填充要求,那么自然脱落:
Consider a platform where sizeof(double) == 8
, sizeof(int) == 4
and the required alignment of double
is 8. malloc()
always returns an address correctly aligned for storing any C type - so in this case a
will be 8 byte aligned. The padding requirements then naturally fall out:
-
为了为
对齐的[0] .D
为8字节,因此必须有7个字节的填充后A [0] .C
;
In order for
a[0].d
to be 8-byte aligned, there must therefore be 7 bytes of padding aftera[0].c
;
为了为 8的[1] .D
是8字节对齐,整体结构尺寸必须的倍数,因此因而一定是4个字节的填充后 A [0] .S
。
In order for a[1].d
to be 8-byte aligned, the overall struct size must be a multiple of 8, so there must therefore be 4 bytes of padding after a[0].s
.
如果你重新排序结构
从最大到最小:
If you re-order the struct
from largest to smallest:
typedef struct structc_tag
{
double d;
int s;
char c;
} structc_t;
...那么唯一需要的填充是在 .C
3个字节,使结构尺寸8的倍数。这导致在结构中的总规模为16,而不是24。
...then the only padding required is 3 bytes after .c
, to make the structure size a multiple of 8. This results in the total size of the struct being 16, rather than 24.
这篇关于混乱的结构成员对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!