Home/Support/Support Forum/Why do I get strange sizeof response when using a double in a structure
Welcome to Digi Forum, where you can ask questions and receive answers from other members of the community.

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

0 votes
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?
asked Feb 7, 2014 in Linux by digiDave New to the Community (20 points)

Please log in or register to answer this question.

2 Answers

+1 vote
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/
answered Feb 7, 2014 by dakotas_dad Veteran of the Digi Community (694 points)
edited Feb 7, 2014 by dakotas_dad
0 votes
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.
answered Feb 7, 2014 by digiDave New to the Community (20 points)
...