From here
first element is char which is one byte aligned, followed by short
int. short int is 2 byte aligned. If the the short int element is
immediately allocated after the char element, it will start at an odd
address boundary. The compiler will insert a padding byte after the
char to ensure short int will have an address multiple of 2 (i.e. 2
byte aligned).
This is how your struct looks like:
+-------+-------+-------+-------+
| Data1 | | Data2 |
+-------+-------+-------+-------+
| Data3 |
+-------+-------+-------+-------+
| Data4 | | | |
+-------+-------+-------+-------+
So padding from char to short
is one byte =>
268624 to 268625 is Data1, from 268625 to 268626 padding to short
.
then 268626 to 268628 short
no padding needed, all aligned to max type of the struct.
From the same reference
There is a way to minimize padding. The programmer should declare the
structure members in their increasing/decreasing order of size
The way to improve your struct is to place char Data4;
directly after char Data1;
This way no memory will be wasted for padding:
struct MixedData
{
char Data1;
char Data4;
short Data2;
int Data3;
}md;
printf("%p %p %p %p", &md.Data1,&md.Data4, &md.Data2, &md.Data3);
0x602270 0x602271 0x602272 0x602274
The basic assumption, that compiler is stick with natural alignment of int on x86