Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit field padding in C

Tags:

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;

       int i;
       printf("sizeof box_porps: %d sizeof unsigned int: %d\n", sizeof(struct box_props), sizeof(unsigned int));
       char *ptr = (char *)&s;
       for (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 struct box_props has size 4 - cannot it just be 2 bytes ? How padding is done in that case ? I'm bit (nomen omen) confused with it.

Thx in advance for all answers

like image 441
JosiP Avatar asked Dec 01 '22 03:12

JosiP


1 Answers

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.

like image 97
Deepu Avatar answered Dec 26 '22 06:12

Deepu