0

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.

learn_develop
  • 1,735
  • 4
  • 15
  • 33
  • 1
    possible duplicate of [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) – Keith Thompson Nov 03 '14 at 05:50
  • Seems quite close to what i may be looking, my 32 bit exe doesn't seem to cause any problem. However, 64 bit does. Will look more closer at the #pragma settings. – learn_develop Nov 03 '14 at 05:57
  • How is the padding after the last member a problem? It's there for a reason. – Keith Thompson Nov 03 '14 at 06:02
  • Actually, this same structure is included in another structure which has few more members after it. The member immediately after the first structure is at a offset of 148 but since we are doing memcpy from a padded structure resulting in a sizeof 152, the content of the member in the second structure gets overwritten with zero and hence, the value resets to zero... – learn_develop Nov 03 '14 at 06:06
  • If the actual problem is that a member is being incorrectly overwritten, you should probably post a new question asking about that, with a self-contained program that illustrates the actual behavior. – Keith Thompson Nov 03 '14 at 07:57

1 Answers1

1

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.

Yorick de Wid
  • 859
  • 11
  • 19