Why do I get strange sizeof response when using a double in a structure

I have defined a structure that includes int’s, chars, etc. When I add a double to the structure it adds 16 bytes to the structure size, however adding more doubles adds the expected 8 bytes each?

Many architectures like to align variables on a particular word boundry. In a structure you can end up with the prior variable ending such that the next double needs to start on a (for example ) even word boundry. SO you could end up with 16 bytes of slack (padding) to bring you to the next word boundry.

This is quite common. What you end up with, if you perform a sizeof, you get one size, and if you take the sum of the sizeof all individual variables, you get a different size. This would be indicative of this padding issue.

Here are a couple of sites that discuss this:

http://en.wikipedia.org/wiki/Data_structure_alignment

http://stackoverflow.com/questions/6968468/padding-in-structures-in-c

http://fresh2refresh.com/c/c-structure-padding/

1 Like

Thank you very much. I also found this on Wiki which I believe is telling me the same thing. The problem cam about because I was doing a checksum on the file/structure, and to avoid including the checksum itself in the checksum calc I did a sizeof(file) - checksumSize. With padding on the end of the file I ended up including the checksum in the calc - not too smart!

In any case, I now injected a variable and calculate the checksum up to the dummy variable - problem solved.

Thanks for your help.