Sign in to follow this  
godsenddeath

strange struct size/behavior (c++)

Recommended Posts

godsenddeath    182
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

Share this post


Link to post
Share on other sites
RDragon1    1205
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.

Share this post


Link to post
Share on other sites
dmatter    4844
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]

Share this post


Link to post
Share on other sites
Erik Rufelt    5901
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this