Alfred Alfred - 10 months ago 45
C Question

strange sizeof result in MVC (alignment?)

The following code gives the result
sizeof(t1)=16 sizeof(t2)=16
I would have expected sizeof(t2)=12 because sizeof(fpos_t)=8 and sizeof(int)=4. Can someone explain this?

int main()
typedef struct {
fpos_t fpos;
char* s;
int a;
} t1;
typedef struct {
fpos_t fpos;
int a;
} t2;
t1 it1;
t2 it2;
printf("sizeof(t1)=%d sizeof(t2)=%d ", sizeof(t1), sizeof(t2));
return 0;

usr usr
Answer Source

For alignment reasons, compiler is free to insert padding. That means the size of a struct is not necessarily equal to the sum of size of individual members. This is explicitly allowed by the C standard.

The only place where padding is not allowed at the start of a struct i.e. before the first member.

From C11 draft,

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

(emphasis mine).