cstructx86-64structure-packing

Sizeof operator returns incorrect size?


Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
Extra bytes when declaring a member of a struct as uint32_t

For some reason, the sizeof operator returns a bogus size for this structure (48 instead of 40):

typedef struct mbdb_file_info {
  uint16_t mode;

  uint32_t unk0;
  uint32_t unk1;
  uint32_t user_id;
  uint32_t group_id;

  uint32_t time0;
  uint32_t time1;
  uint32_t time2;

  uint64_t length;
  uint8_t flag;
  uint8_t property_count;
} mbdb_file_info;

So here is a simple test:

printf("%ld %ld %ld %ld: %ld", sizeof(uint8_t),
                                sizeof(uint16_t), 
                                sizeof(uint32_t),
                                sizeof(uint64_t),
                                sizeof(mbdb_file_info));

Which prints:

1 2 4 8: 48

How does this happen? If you add all the sizes together you get 40, not 48. Where on earth does the 48 come from?

And if it's some weird x86-64 perk, how do I ensure that the all the fields of the structures occupy the amounts I want them to occupy (I'm casting a bunch of bytes to this structure)?


Solution

  • The compiler may append some bytes in the middle of the struct in order to align the struct members. The size of the struct is at least the sum of he members' size, but not limited to it.