I have a C structure comprising of a couple of elements. When i type offsetof() on the last element of the structure, it shows 144 and sizeof() the last element is 4. So, I was assuming the size of the structure is 148. However, running sizeof() on the structure itself returns a value of 152. Is there something I am misinterpreting about the offset? Shouldn't the size of the structure be 148 instead of 152? Is there some sort of padding that is being applied to fit the byte? I am running on a 64bit platform on Ubuntu 14.
Struct A{
// few elements
};
Struct B{
Struct A;
<type> C;
<type> D;
// few more elements
};
element C is at a offset of 148(may be because padding is not applied), but the sizeof struct A is 152(quite possibly due to padding) and hence, when memcpy is performed, the value assigned to element C gets zeroed out.
UPDATE : Just verified sizeof() element C is 4 bytes and hence, it makes sense it gets included immediately after 148th offset.
There is no padding, al least not before or after the structure. However if you use different datatypes within the same structute sometimes an alignment is added for performance. This is a compiler settings and if you want you can disable it.