strange struct size/behavior (c++)

Started by
3 comments, last by hughiecoles 15 years, 8 months ago
I'm in the middle of writing a .BMP loader, which is a fairly simple task, but when I create the header struct, the size is wrong, and no matter what i do, it refuses to act as it should. the struct is as follows struct Header { short MagicNumber; int FileSize; int Reserved; int DataOffset; }; this should add up to 14 bytes, but it won't. it shows sizeof(Header) == 16 I'm using my laptop with 32 bit windows vista, MSVS professional. the only way i can get it to add to 14 is if I change all the members to unsigned chars of equivilent size, i've even double checked the sizes of int and short to make sure. the second struct, BitmapInfo lines up fine, does anyone know what could be wrong? EDIT: also, it acts weirdly when I take out certain members, such as, if I comment out the short, it shoots down to 12, which is right, but that would imply the short is 4 bytes, when it's only 2
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried
Advertisement
Most processors are more performant when data is aligned in memory. Therefore, compilers insert padding between data members so that the next member is optimally aligned. Padding may also be inserted at the end of a struct so that arrays of that type have each element aligned.
It's called byte padding and it's used to maintain a certain byte alignment for efficiency. In this case the 2 byte short is being padded with two extra duff bytes to align everything to a 4 byte boundry.

There are compiler specific ways to force byte padding off. However it's not usually a problem, the common issue is when you're directly populating a struct from a binary file - the better solution would just be to not do that, you could read bytes to initialise attributes one at a time instead.

Also, as you're on windows, Microsoft actually provide structs for bitmap reading so you don't have to, in windows.h unsurprisingly. [smile]
Your compiler is aligning the later members to 4-byte addresses. Even though MagicNumber only uses 2 bytes, FileSize will start 4 bytes later, leaving a 2-byte unused space in between.
You can fix it by adding #pragma pack(1) before your struct.

Check this link for more information: http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx
thanks, you guys were very, very helpful
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried

This topic is closed to new replies.

Advertisement