cstructpadding

C Structure Padding. Nested Structures


struct Y{
  int int_one;
  int int_two;
  void * pointer;
}

struct X{
    char char_one;
    char char_two;
    struct Y y_structures[20];
 }

the padding is different on 32 and 64 bit machines. I don't know why. As far as I know the padding should be as follows :

 0x0 char_one <br>
 0x1 char_two <br>
 0x4 y_structures[0].int_one <br>
 0x8 y_structures[0].int_two <br>
 0x12 y_structure[0].pointer <br>

the structure on 32 bit is similar as mentioned above but on 64 bit machine the difference between addresses of char_two and y_structures[0].int_one is 7 bytes. I think that it should be 3 bytes because the type to be aligned after char_two is an int of the y_structures[0] and it's size is 4 on both architectures. Kindly help


Solution

  • The problem is not the int, it's the pointer. pointer have a size of 8 bytes on 64bit machines, therefore they must start at a memory address mod 8.

    0x0 char_one
    0x1 char_two
    0x8 y_structures[0].int_one
    0x12 y_structures[0].int_two
    0x16 y_structure[0].pointer
    0x24 y_structures[1].int_one
    0x28 y_structures[1].int_two
    0x32 y_structure[1].pointer
    ...
    

    so there must be 6 padding bytes. This is not necessary on 32 bit machines, because there pointer only have 4 byte.