I use a datastructure in my project and in the context of a paricular structure i have a doubt about strucure padding. First Look at the strucure given below. I use Visual Studio 2008 compiler.
typedef struct tagDATA_PACK
{
DWORD dDataLength;
BYTE bFlags;
BYTE bAttrib;
BYTE bOffset;
}DATA_PACK;
Question1: How much is the size of the above structure?
it shows 8 bytes. it is correct. But,
consider the modified structure given below?
typedef struct tagDATA_PACK
{
DWORD dDataLength;
BYTE bFlags;
}DATA_PACK;
here the size is same as the above 8byte structure.
My doubt here is, where would be the compiler adding the extra 3bytes?
is it after BYTE bFlags or before it?
All your answer is greatly appreciated.
Alignment and padding for structs and classes is not specified by the standard. It’s entirely down to the compiler. However, all sane compilers follow the underlying platform ABI. In your case the platform is Windows, and the Windows platform ABI is adhered to.
The padding in this case, for both structs, is after the last member. The first struct has one extra padding byte, and the second struct has three extra padding bytes.
The largest type in the struct has size 4. And that means that the overall size will be a multiple of 4. For both structs, the smallest multiple of 4 that accommodates the struct is 8.
Each data type has an alignment property. A 4 byte data type has alignment of 4. A 2 byte data type has an alignment of 2. A type with alignment of 4 is aligned when placed on a 4 byte offset from the start of the struct. A type with alignment of 2 is aligned when placed on a 2 byte offset from the start of the struct. And so on.
Members are placed at the smallest offset that respects both the order of declaration of members, and the alignment property of the members.
For an example with padding internal to the struct consider this struct
The alignment of
cis 1, and the alignment ofiis 4. So,cis placed on a 1 byte boundary, andimust be placed on a 4 byte boundary. That means thatcwill have offset 0, then there will be 3 padding bytes, and theniwill be laid out at an offset of 4.