Padding
Struct need to be a multiple of the bigger data type in the struct. So if you have a struct with a int64_t and a short, the struct will be padded to be a multiple of 8 bytes. So the struct will be 16 bytes, even though the total size of the struct is 14 bytes.
cpp
struct A {
int64_t a; // 8 bytes
int b; // 4 bytes
short c; // 2 bytes
};
// total
// 8 + 4 + 2 = 14 bytes
// but in reality it is 16 bytes
// because of padding, which is 2 bytes, to make
struct A {
short c; // 2 bytes
int64_t a; // 8 bytes
int b; // 4 bytes
};
// total
// 2 + 8 + 4 = 14 bytes
// but in reality it is 24 bytes
// because first short is padded to 8 bytes (+6 bytes)
// and then the int64_t is padded to 8 bytes (+0 bytes)
// and then the int is padded to 8 bytes (+4 bytes)
// to make the size of the struct a multiple of 8 bytes
Solutions
- order the struct from biggest to smallest
- use
#pragma pack(1)
to disable padding
cpp
#pragma pack(push, 1)
struct A {
short c; // 2 bytes
int64_t a; // 8 bytes
int b; // 4 bytes
};
#pragma pack(pop)
// total
// 2 + 8 + 4 = 14 bytes
// then the size of the struct is 14 bytes
// because of padding, which is 0 bytes, to make
// the size of the struct a multiple of 1 bytes