Hi guys, i have one question regarding alignment. Assume that you have the following struct:
struct align1
{
double a;
char b;
int c;
short d;
};
Also assume:
sizeof(double): 8
sizeof(int): 4
sizeof(char): 1
sizeof(short): 2
i would expect:
sizeof(align1): 8 + (char padded to->) 4 + 4 + 2 = 18 bytes
but i get:
sizeof(align1): 8 + (char padded to->) 4 + 4 + (short padded to->) 4 = 20 bytes
So what i don't understand is why the compiler pads the structure in the end? Theoretically the compiler could occupy the 2 wasted bytes
of the struct with 2 chars, why waste them on padding?
To make the question more clear if we had:
struct align1 var1;
char a;
char b;
we would need to allocate only 20bytes; but with the strategy of the compiler we would need 24 bytes. So what i want to learn is
why gcc is making this choice.
The program to test all this follows:
#include <stdio.h>
struct align1
{
double a;
char b;
int c;
short d;
};
struct align2
{
double a;
char b;
short d;
int c;
};
struct align3
{
double a;
int c;
char b;
short d;
};
int main()
{
printf("sizeof(double): %d\nsizeof(int): %d\nsizeof(char): %d\nsizeof(short): %d\n",
sizeof(double),sizeof(int),sizeof(char),sizeof(short));
printf("minimum space required: %d bytes \n", sizeof(double)+sizeof(int)+sizeof(char)+sizeof(short));
printf("allignment1 costs: %d bytes\n", sizeof(struct align1));
printf("allignment2 costs: %d bytes\n", sizeof(struct align2));
printf("allignment3 costs: %d bytes\n", sizeof(struct align3));
return 0;
}
I have read the following articles {but i still haven't figured out what i am asking}:
[1] http://en.wikipedia.org/wiki/Packed
[2] http://www-128.ibm.com/developerworks/library/pa-dalign/
[3] http://msdn.microsoft.com/en-us/library/ms253949.aspx