cstructbit-fields

Bit field padding in C


Continuing my experiments in C, I wanted to see how bit fields are placed in memory. I'm working on Intel 64 bit machine. Here is my piece of code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char **argv) {
       struct box_props {
         unsigned int opaque       : 1;
         unsigned int fill_color   : 3;
         unsigned int              : 4; 
         unsigned int show_border  : 1;
         unsigned int border_color : 3;
         unsigned int border_style : 2;
         unsigned int              : 2; 
       };
       
       struct box_props s;
       memset(&s, 0, 32);
       s.opaque = 1;
       s.fill_color = 7;
       s.show_border = 1;
       s.border_color = 7;
       s.border_style = 3;
    
       printf("sizeof box_porps: %d sizeof unsigned int: %d\n", sizeof(struct box_props), sizeof(unsigned int));
       char *ptr = (char *)&s;
       for (int i=0; i < sizeof(struct box_props); i++) {
          printf("%x = %x\n", ptr + i, *(ptr + i));
       }

       return 0;
}

and here is an output:

sizeof box_porps: 4 sizeof unsigned int: 4
5be6e2f0 = f
5be6e2f1 = 3f
5be6e2f2 = 0
5be6e2f3 = 0

And here is the question: why does struct box_props have size 4 - can't it just be 2 bytes? How is the padding done in that case? I'm a bit (nomen omen) confused with it.


Solution

  • Even though the total requirement is just 2 Bytes (1+3+4+1+3+2+2) in this case, the size of the data type used (unsigned int) is 4 bytes. So the allocated memory is also 4 Bytes. If you want just 2 Bytes allocated use unsigned short as your data type and run the program again.