[英]Finding the correct size of a misaligned structure
typedef struct structA
{
char C;
double D;
int I;
} structA_t;
Size of this structA_t structure: 此structA_t结构的大小:
sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) = 1 + 7 + 8 + 4 = 20 bytes
sizeof(char)+ 7字节填充+ sizeof(double)+ sizeof(int)= 1 + 7 + 8 + 4 = 20字节
But this is wrong , the correct is 但这是错误的,正确的是
24
24
. 。 Why?
为什么?
There is most likely 4 byte padding after the last ìnt
. 目前最有可能是最后一次后4个字节的填充
ìnt
。
If sizeof(double) == 8
then likely alignof(double) == 8
also on your platform. 如果
sizeof(double) == 8
则可能在您的平台上alignof(double) == 8
。 Consider this situation: 考虑这种情况:
structA_t array[2];
If size would be only 20, then array[1].D
would be misaligned (address would be divisible by 4, not 8 which is required alignment). 如果size只有20,则
array[1].D
将不对齐(地址可以被4整除,而不是8,这是必需的对齐)。
char = 1 byte char = 1个字节
double = 8 bytes double = 8个字节
int = 4 bytes int = 4个字节
align to double => 对齐double =>
padding char => 1+7
padding double => 8+0
padding int => 4+4
=> 24 bytes => 24个字节
or, simply put, is the multiple of the largest => 3 (the number of fields) * 8 (the size of the largest) = 24 或者,简单地说,是最大的倍数=> 3(字段数)* 8(最大的大小)= 24
我的猜测是你的系统中int
的大小是4字节,所以int也必须填充4字节,以实现8字节的字大小。
total_size=sizeof(char) + 7 Byte padding + sizeof(double) + sizeof(int) + 4 Bytes padding = 24 Bytes
Good article on padding/alignment: http://www.drdobbs.com/cpp/padding-and-rearranging-structure-member/240007649 关于填充/对齐的好文章: http : //www.drdobbs.com/cpp/padding-and-rearranging-structure-member/240007649
Because of the double member it forces everything to be eight byte aligned. 由于双成员,它强制所有内容都是八字节对齐的。
If you want a smaller structure then following structure gives you 16 bytes only! 如果你想要一个更小的结构,那么下面的结构只给你16个字节!
typedef struct structA
{
int I;
char C;
double D;
} structA_t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.