简体   繁体   中英

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:

sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) = 1 + 7 + 8 + 4 = 20 bytes

But this is wrong , the correct is

24

. Why?

There is most likely 4 byte padding after the last ìnt .

If sizeof(double) == 8 then likely alignof(double) == 8 also on your platform. 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).

char = 1 byte

double = 8 bytes

int = 4 bytes

align to double =>

padding char => 1+7 

padding double => 8+0

padding int => 4+4

=> 24 bytes

or, simply put, is the multiple of the largest => 3 (the number of fields) * 8 (the size of the largest) = 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

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!

typedef struct structA 
{
   int         I;
   char        C;
   double      D;
} structA_t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM