Reputation:
In a previous post, I have understood why we must take an alignment for a structure equal to the biggest attribute size.
Now, I would like to know why, once we have chosen this alignment, we have to do padding so that the total structure size is a multiple of the structure alignement and not the processor word size.
Here an example :
#include <stdio.h>
// Alignment requirements
// (typical 32 bit machine)
// char 1 byte
// short int 2 bytes
// int 4 bytes
// double 8 bytes
typedef struct structc_tag
{
char c;
double d;
int s;
} structc_t;
int main()
{
printf("sizeof(structd_t) = %d\n", sizeof(structd_t));
return 0;
}
We could think that size of structd_t is equal to 20 bytes with :
char c;
char Padding1[7]
double d;
int s;
because we have taken a structure alignement equal to 8 (double d).
But actually, total size is equal to 24 because 20 is not a multiple of 8 and we have to do padding after "int s" (char Padding2[4]).
If I take an array of structure, the first elements of each structure is at good adresses for a 32 bits processor (0, 20, 40) because 20, 40 ... are multiple of 4 (processing word size).
So Why have I got to do padding for having a multiple of 8 (the structure alignement), i.e 24 bytes in this example, instead of having 20 bytes (which gives good adresses for the 32 bits processor (word size = 4 bytes) : 0, 20, 40 ... ?
Thanks for your help
Upvotes: 1
Views: 583
Reputation: 7923
Consider struct_t array[n]
. Would the size of structure be 20 (not multiple of 8), the second element were aligned at a 4-byte boundary.
To clarify: Let array[0]
be at address 0
. If size of the structure is 20
, array[1]
starts at address 20
, and it's d
lands at address 28
, which is not a proper alignment for a double.
Upvotes: 3