Skip to main content
gamedev.net
🔒 Locked

Alignment Problem

Started by Kafeen Sep 18, 2005 at 4:59 AM 2 replies 850+ views
Original Post
Kafeen
Kafeen
Hi, I've got a problem with a current project I was wondering if anyone could shed some light on. I start be reading in a file, the format for this is already set, It's not something I have the option of hanging. The file loads into a buffer with no issues. Since the buffer I load it in to is jsut a void* I want to cast it so I can pull the data out. I have a pointer of the correct type, I set it to the start of the buffer. No problems so far. When I tried getting the data out of the structure I noticed the 3 item in the structure and everything after it was wrong. The start of the structure lay at 0x......40 in memory (exact address isn't importent). The contents was layed out like this: DWORD (0x......40) WORD (0x......44) - Correct WORD[2] (0x......46 & 0x......48) - Correct DWORD (0x......4c) - Wrong, it should be at 0x......4a If one of the WORDs above the last DWORD is removed then it sits at 0x......48 as you'd expect, it just doesn't like sitting 10Bytes ahead of the start of the structure where I need it. To me it looks like the last DWORD is being forced onto a 4Byte boundry, but why? It's not something I've done and the WORD above isn't so it doesn't look like a global setting. Anyone know what's going on?
SirLuthor
SirLuthor
By default, IIRC, structs and classes are aligned on 4 byte boundaries (or the natural size of the processor?), so it's hardly surprising that the third WORD gets padded out to a full 4 bytes, before the DWORD. You'd be better served by moving the last DWORD to right after the first one. Or even better, changing some of the members of the struct so that it fits properly to a 4 byte alignment. Probably should make that first WORD a DWORD, you don't lose anything by doing that, because when your struct is fetched from memory, you will be fetching an extra 2 bytes of empty memory anyway.

In general though, you should never really be relying on the ordering and placement of members if there is any other way to possibly do what you want.
Free speech for the living, dead men tell no tales,Your laughing finger will never point again...Omerta!Sing for me now!
Kafeen
Kafeen
Unfortunaly if I do that then the file I'm reading in won't match the format in the code. I don't have the option of changing the file.
Kafeen
Kafeen
Nevermind, I just needed to put #pragma pack( push, 1 ) around the structure.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.