64位机器上的结构填充 [英] structure padding on 64bit machine
问题描述
struct A
{
uint32_t var1;
uint32_t var2;
uint32_t var3;
uint32_t var4;
uint32_t var5;
};
在上述结构中,编译器不填充并分配 20 个字节.
In the above structure compiler does not pad and allocates 20 bytes.
现在我们有另一个结构,它包含一个 8 字节变量而不是两个 4 字节.在这种情况下,编译器填充并分配 24 字节给这个结构.
now we have another structure which contains one 8 byte variable instead of two 4 bytes.In this case compiler pads and allocates 24 bytes to this structure.
struct B
{
uint32_t var1;
uint32_t var2;
uint32_t var3;
uint64_t var5;
};
为什么会有这种行为?如果编译器将数据对齐到 8 字节边界,那么第一个结构中应该有 4 个字节的填充,并且应该在这种情况下,不要填充第二个结构.并且如果编译器将数据对齐到 4 字节边界,那么为什么在第二个结构中有 4 字节的填充?
why there is such behaviour? If compiler align the data into 8 byte boundry then there should be padding of 4 bytes in the 1st structure and should not pad the 2nd structure in such case. and also if compiler align the data into the 4 byte boundry then why there is padding of 4 byte in the 2nd structure ?
编译器:GCC平台:64位linux,x86_64
compiler: GCC Platform: 64 bit linux , x86_64
推荐答案
对齐规则(在 x86 和 x86_64 上)通常是根据变量的大小对齐.
The rule for alignment (on x86 and x86_64) is generally to align a variable on it's size.
换句话说,32 位变量在 4 个字节上对齐,64 位变量在 8 个字节上对齐,依此类推.
In other words, 32-bit variables are aligned on 4 bytes, 64-bit variables on 8 bytes, etc.
在你的第二种情况下,4 个字节的填充被添加到
In your second case, 4 bytes of padding are added between
uint32_t var3;
uint64_t var5;
让 var5
在 8 个字节上对齐.
to get var5
to align on 8 bytes.
因此,最好将数据成员从大到小排序(但由于数据的局部性、可读性等原因,这并不那么简单).
For this reason it is better to order data members from largest to smallest (but it's not that simple due to data locality, readability etc.).
这篇关于64位机器上的结构填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!