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.
Your struct
contains short
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With