Reputation: 1552
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.
Upvotes: 4
Views: 581
Reputation: 5744
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.
Upvotes: 8
Reputation: 54074
Because a 32-bit cpu likes to access the data in 4 byte chunks
Not exactly. Strictly speaking a memory access is aligned (because here you talk about alignment) when the variable that you access is N
bytes long and the variable address is N
-bytes aligned.
So it does not mean that it is 4-bytes aligned. Could be 2 bytes aligned as in your case where you declare types short
and the data range is 2 bytes.
Upvotes: 2
Reputation: 96233
You're already accessing memory in one and two byte increments in the struct
so you won't hurt performance any further by aligning the struct on 6 bytes vs 8 so the compiler opts to save the space. If you just never make assumptions about struct alignment and let the compiler do the right thing, you won't have to worry about it in practice.
Upvotes: 4