Friday, July 31, 2009

C code - Acting weirdly Plz can anyone solve this?

#include%26lt;stdio.h%26gt;


struct test


{


unsigned short int a;


unsigned int b;


};





typedef struct test test;





int main()


{


printf("\n\nSize of test = %d\n",sizeof(test));


}





The expected answer was 6 but i am getting it as 8 !!!





I tried this with Microsoft VC++ 6.0 and GCC both give the size as 8...





Why is that so..

C code - Acting weirdly Plz can anyone solve this?
This is because of address alignment requirements of of variables, in the structure.





int starts on a multiple of 4 boundary


double starts on a multiple of 8 boundary and so on.





Try changing of the second variable in your structure as double and you will see the size as 16.
Reply:I tried this also with gcc and got the same result.





I tried a few experiments and have come to the conclusion that in a struct, the compiler will pack the struct in multiples of 32 bits (4, 8, 12, etc). However I tried making the struct entirely of 3 shorts, which gave me a size if 6. So if the largest data member is 2 bytes, then the compiler will pack the struct in multiples of two. Otherwise, the compiler will pack it in multiples of 4 bytes. e.g, a struct with a double and a short or int will have a size of 12.





In other words, it seems the problem is not with your code. The problem is one of compiler behavior.
Reply:I think in VC++ , all data type have 4 byte size, thats why u r getting 8 as answer, I am having a bit of knowledge that in VC++ compiler asign each data type 4 byte size so that compiler process faster. it access data as 4 byte at a time. that means if any data type is having size less than 4 byte than also it will be allocated into 4 byte of size.
Reply:The compiler inserts 2 dummy bytes between members ‘a’ and ‘b’.





The reason is that the compiler will align member variables to a multiple of the pack size or a multiple of the type size, whichever is smallest.





The default pack size in visual studio is 8 bytes.

daffodil

No comments:

Post a Comment