Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About struct padding

Suppose we have a packet

struct Foo
{
    short size; // 2
    short type; // 2
    BYTE  data; // 1
    //1 byte padding not 3?
};

After compilation it's 6 bytes long with 1 byte padding added at the end of the struct. Isn't the compiler supposed to add 3 bytes padding so that the structs size is 8 bytes long? Because a 32-bit cpu likes to access the data in 4 byte chunks

Btw with #pragma pack(1) it's 5 bytes long, as expected.

like image 442
Christian Avatar asked Dec 08 '22 21:12

Christian


1 Answers

Your struct contains shorts which means that those will likely need to be aligned on a two byte boundary. If you were to create arrays of this struct with no padding, every other element would end up with the shorts incorrectly aligned which might crash or be slow.

Padding exists for the purpose of safety and performance. On certain architectures an unaligned read causes a crash. So the compiler pads the struct so that it's members align on addresses dividable by their size. Apart from that the compiler will have little reason to add extra padding just to align the entire struct on the native word boundary. So it will add only one byte in your case.

Try having an int in your struct. This should change the padding to have an additional 3 bytes of padding. Also having the int in between two bytes will make padding between the bytes.

The compiler is free to make whatever choice it wants regarding padding and unless you specify packing explicitly. Different things will happen on different architectures and with different compilers.

like image 74
Dervall Avatar answered Dec 25 '22 12:12

Dervall