2

I was going through the lecture notes for the MIT open courseware on practical programming in C about structure padding:

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-087-practical-programming-in-c-january-iap-2010/lecture-notes/MIT6_087IAP10_lec07.pdf

In it, I understood why the following structure has a size of 16:

struct foo { 
   short s;             
   union {
     int i;
     char c;
   }u;      
   unsigned int flag_s : 1;
   unsigned int flag_u : 2;
   unsigned int bar;
}

To minimize the size of the structure, the author rearranged the fields from largest to smallest in size:

struct foo {              
   union {
      int i;
      char c;
   }u;   
   unsigned int bar;    
   short s;
   unsigned int flag_s : 1;
   unsigned int flag_u : 2;
}

And the author said that the size of the structure should now be 12. However, on my Windows 32 bit machine, I'm still getting an output of 16 for the struct size. Why is that?

It's only when I move the 'short s' field below the bit fields that I get a struct size of 12. Is this because the bit fields must start at a 4 byte boundary on account of being an unsigned integer? Therefore in the structure above, there will still be 2 bytes of padding after the 'short s' field?

1 Answer 1

0

According to the C language standard, bit fields layout is implementation dependend. So it is fine that the size of this struct was 12 bytes on the author's machine but it is 16 on yours(however, it is strange that in the lecture they claim that its size is 12 bytes without pointing out that it is compiler dependend).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.