Search code examples
cstructalignmentpadding

Why c struct padding is required at __last__ element


I am aware of padding, and its rules, why it requires etc.

My question is given struct,

struct my_struct {
   int a;
   char c;
};

In this case start address of c is word align, but still compiler added 3 bytes (assuming 4 as word size) padding. with no element after c and why we need these 3 bytes? I checked following,

int g_int1;
struct my_struct st;
int g_int2;

by above what I mean is my rest of variable declarations are not dependent on word align-ness of previous variable size. compiler always try to align next variable irrespective of its global or local auto var.

I cant see any reason with endian-ness since this is char and for one byte it don't matters. what reason I think is instead of checking last element condition compiler always add padding whenever required.

what can the valid reason?


Solution

  • Because if sizeof(my_struct) was 5 rather than 8, then if you did this:

    my_struct array[2];
    

    then array[0] would be word-aligned, but array[1] would not be. (Recall that array lookup is done by adding multiples of sizeof(array[0]) to the address of the first element.)