PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

ipaq 4155 datatype misalignment error

I am having a problem with the pocket pc 2003 and a nasty data misalignment error. I have narrowed the problem down to the following lines of code in my CBitmap class.

Here is my LoadDIB class first. The errors keep occurring with malloc and realloc.

Code:

first my declaration in .h
LPBYTE lpDIB;

now the LoadDIB function:
//////////////////////////////////////////////////////////////////////
// CBitmap::LoadDIB
//
// Reads a bitmap from disk and converts it to a DIB buffer.
//
BOOL CBitmap::LoadDIB(LPCTSTR szFileName)
{
HANDLE hFile;
BITMAPFILEHEADER bfh;
LPBYTE lpTemp = NULL;
WORD wPaletteSize = 0;
DWORD dwBitsSize = 0;
BOOL bRet;

//open the file
hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}

//read the header
bRet = ReadFile(hFile, &bfh;, sizeof(BITMAPFILEHEADER), &dwImageSize;, NULL);
if ((bRet == FALSE) || (dwImageSize != sizeof(BITMAPFILEHEADER)))
{
CloseHandle(hFile);
return FALSE;
}

//is this a valid bitmap file?
if ((bfh.bfType != 0x4d42) || (bfh.bfReserved1 != 0) || (bfh.bfReserved2 != 0))
{
CloseHandle(hFile);
return FALSE;
}

//allocate memory for the bitmap data
lpDIB = (LPBYTE) malloc(sizeof(BITMAPINFO));
if (lpDIB == NULL)
{
CloseHandle(hFile);
return FALSE;
}

//read in the BITMAPINFOHEADER
bRet = ReadFile(hFile, lpDIB, sizeof(BITMAPINFOHEADER), &dwImageSize;, NULL);
if ((bRet == FALSE) || (dwImageSize != sizeof(BITMAPINFOHEADER)))
{
CloseHandle(hFile);
free(lpDIB);
return FALSE;
}

if (((LPBITMAPINFOHEADER)lpDIB)->biSize != sizeof(BITMAPINFOHEADER))
{
CloseHandle(hFile);
free(lpDIB);
return FALSE;
}

wPaletteSize = PaletteSize((LPSTR)lpDIB);
dwBitsSize = ImageHeight() * BytesPerLine((LPBITMAPINFOHEADER) lpDIB);

//realloc the DIB buffer
lpTemp = (LPBYTE) realloc(lpDIB, sizeof(BITMAPINFOHEADER) + wPaletteSize + dwBitsSize);
if (lpTemp == NULL)
{
CloseHandle(hFile);
free(lpDIB);
return FALSE;
}

lpDIB = lpTemp;

//read palette if one is present
if (wPaletteSize > 0)
{
bRet = ReadFile(hFile, ((LPBITMAPINFO)lpDIB)->bmiColors, wPaletteSize, &dwImageSize;, NULL);
if ((bRet == FALSE) || (dwImageSize != wPaletteSize))
{
CloseHandle(hFile);
free(lpDIB);
return FALSE;
}
}

if (bfh.bfOffBits > 0)
{
if (SetFilePointer(hFile, bfh.bfOffBits, NULL, FILE_BEGIN) == 0xffffffff)
{
CloseHandle(hFile);
free(lpDIB);
return FALSE;
}
}

//read the image data
bRet = ReadFile(hFile, BitmapDataIndex((LPSTR)lpDIB), dwBitsSize, &dwImageSize;, NULL);
if ((bRet == FALSE) || (dwImageSize != dwBitsSize))
{
CloseHandle(hFile);
free(lpDIB);
return FALSE;
}

//close file and return
CloseHandle(hFile);
return TRUE;
}

lastly, the destructor for the CBitmap class:
//////////////////////////////////////////////////////////////////////
// CBitmap Destructor
//
// This function is called when the class is terminated.
//
CBitmap::~CBitmap()
{
if (lpDIB != NULL)
free(lpDIB);

if (hSourceDC != NULL)
{
SelectObject(hSourceDC, hOldBitmap);
DeleteObject(hOldBitmap);
DeleteDC(hSourceDC);
}
}

The problem occurs EVERY time if I try freeing the memory set to lpDIB. If I comment out the
free(lpDIB).

Then the problem doesn't follow, but I have a memory leak. I've stumped on this one. Any help would be greatly appreciated.
Kevin Gelso · 05 Sep 2004, 15:35 UTC
Put this down into the devolopers forum. Also when putting your code it makes it easier to read if you do [ code] then put ur code here [/code ] Just type that in without the spaces in the tag.
Put code tag in, moved to Dev forum.
ramses · 05 Sep 2004, 17:50 UTC — different sizes of structs
Sorry, I had two postings of the code :oops:
Here, is how my code is laid out

I have a CBitmap class as the base class.
Then I have a class called CSprite that encapulates the CBitmap class. After CSprite, then I have a class called CAnimSprite which encapsulates the CSprite class.

Here are the destructors:

Code:
//////////////////////////////////////////////////////////////////////
// CAnimSprite Destructor
//
// This function is called when the class is terminated.
//
CAnimSprite::~CAnimSprite()
{
for (int n = 0; n < NUM_FRAMES; n++)
delete sprites[n];
}

//////////////////////////////////////////////////////////////////////
// CSprite Destructor
//
// This function is called when the class is terminated.
//
CSprite::~CSprite()
{
DeleteDC(hdcUnder);

delete DestRect;
delete Rect1;
delete Rect2;
}


Here's how the code works. I declare a variable in the .h file first
Code:
CAnimSprite *testVar;


Next I initialize the variable with the new operator
Code:
testVar = new CAnimSprite(hdc)


If I have two or more CAnimSprites objects then I get the data misalignment error. It's a really weird error. I can post more of the code if necessary.[/code]
I have seen data alignment errors in two cases

1) you alloc a byte array with new then typecast it to a word or dword pointer and deref it

2) you use pragma pack(1) around classes to pack the data without pushing and popping the packing alignment, thereby effecting all following classes and structs being compiled

I suggest you check your code and all headers for both.
ramses · 06 Sep 2004, 07:10 UTC — data misalignment
From what I have seen in the code, I think that my realloc is the thing causing my problems. If I change the code to simply not use realloc, then the problem no longer occurrs. I just have to figure out a good way to move the data in lpDIB over to a variable then back into lpDIB without using realloc. I did some reading on http://www.developer.com/ws/pc/article.php/3069341 about good memory practices on the pocket pc and it mentions to get rid of the C calls. I think I'll just make some changes to fit with the article if possible.
I just read the article you mentioned and I can't believe that it said to not use malloc(). I've got lots of code that uses it and one game that malloc/frees tons of memory (well over 10mb). None of this has ever caused a problem. No leaks, drips, runs or errors.
For your specific situation, keep the header/palette information apart from the bitmap data. The header shouldn't stored as BITMAPINFOHEADER, but as a more generic structure.. read in BITMAPINFOHEADER and then translate. This is helpful when you start reading bitmaps of other types... such as JPG or TGA. With your header in a generic format and the bitmap data in its own array, your CBitmap class can work for more than one file type. Change your ::LoadDIB(char *filename) to ::FromFile(char *filename) and have that function look at the extension (or similar) to determine the filetype and then call the specific function for that filetype. It sounds like more work, but three years down the road when you are using this class for 10 different formats, you'll be happy you got it right to start! My 'bitmap' class was started in '91 with Win31 and I still use it today. Get these basic classes solid and you can use them for years.

Cheers,

rcp
ramses · 06 Sep 2004, 16:31 UTC — excellent idea
I didn't even think of using different image types until now. That would actually work out well. I also found information on how to load a bitmap from file from a good site.

http://www.gamedev.net/reference/articles/article1966.asp

Reading in multiple file formats does seem like more work, however, it will offer me more flexebility in the future. I think I'll go ahead and start working on it!
ramses · 07 Sep 2004, 19:43 UTC — small fix found for data misalignment
Here is a small fix that I found to correctly align the data:
Code:
#define roundSz(n) ((n+7) & ~ 7)


So, around the malloc and the realloc I places roundSz(). I no longer get the data misalignment error, but I get this one in its place:

First-chance exception in program.exe: 0xC0000005: Access Violation. I think I'm making some progress, but this one is going to take some time to fix.
Code:
#define roundSz(n) ((n+7) & ~ 7)


Eek, you're trying to fix the symptom, not the problem. By doing that, you could be reading/writing off of the end of your memory block, and also passing back a bad pointer to the memory manager.

Idea: you're potentially freeing the lpDIB more than once - if it fails to load you do free(lpDIB) and then in the destructor, you call it again because lpDIB hasn't been nulled. This tends to not make the memory manager happy.

Also, are you sure that the pointer returned by realloc isn't aligned?
refractor:
You are touching on what I was thinking... realloc usually gives back the same pointer, and I am pretty sure those are always DWORD aligned. What was strange was that he said the misalign exception came on the free(). Can't think of any reason for that to happen, unless... he overwrote memory and nuked the linked list for the heap. Then during the free(), the free() routine got a 'next address' and tried to update the link and _that_ address was bogus and, co-incidently, not aligned for DWORD access. So misalignment was really another way of saying, heap list is bad. That was my rational for making two mallocs, the second being big enough to hold the bitmap at its theoretical size... not what the header or file said. That is how my texture (bitmap) classes work and they seem to be fine...

ramses:
try adding 32 to your malloc size, and do two, one for the header and one for the bitmap. You might also calculate the theoretical size of the bitmap, ie; Width*Height*BytesPerPixel, and use that for the malloc size.

-rcp
ramses · 08 Sep 2004, 04:37 UTC — ipaq data misalignment
I created two mallocs today just to see if realloc was causing my problem today as well. I realize that this wasn't a real attempt to solve the problem. I was seeing if it had any affect on the data misalignment problem. The sizeOf fix actually did very little and I still have a problem. I even tried to malloc twice instead of using the realloc. That didn't do anything either. I will follow your advice and try adding 32 to the malloc and then calculate the theoretical value for the bitmap.
ramses · 08 Sep 2004, 05:06 UTC — changing theoretical size
I padded the mallocs with 32 and changed the equasion to the theoretical size and I didn't have any results. In fact, after I changed the equasion to load height*width*bitsize then it won't even load my images anymore. I will continue to look to see where the problem is.
:?: Why are you writing your own image loader? Just use a function that is already tested, or use libpng or jpg for example, they have loaders for a few formats. Would you rather be writing a game or an image loader? Its far easier to use free and tested code out there than roll your own.

8O Also the roundSz is a very bad idea, take that code out unless you account for it in the allocation (by adding 32 as others suggest).

:!: Lastly note that height*width*bitsize is different than Width*Height*BytesPerPixel, which might be your problem there.
ramses · 14 Sep 2004, 19:46 UTC — image loader
The program itself is not an image loader. I am using a library that I got out of a pocket pc book and I have been trying to create a game with. The main problem right now is that when I try to simply free the variable lpDIB in the destructor, I get a datatype misalignment error. I thought at first it might have something to do with this particular function but after going through several debug sessions with it, and thanks to many great comments here, I don't think that the LoadDIB class is really the issue but it is other things that might be affecting the memory.
For anybody that has seen the book it is called "Pocket PC Game Programming using the Windows CE Game API". It is actually a great book in my opinion because it covers most of the main issues of game programming like sound, graphics, etc. The problem is that inside of his book, there is a problem with the Game Library that he writes that causes a data misalignment error or it changes to a first-chance exception if I use the roundsz() function listed above. I agree roundsz() is NOT a good solution but it was an attempt to see what was going on. I don't know if I can post the code to the library due to legal reasons, but I can post my own to show how I am calling the library. If I need to I will definately do so.

Here is the function for BytesPerLine() in CBitmap.cpp
Code:
int CBitmap::BytesPerLine(LPBITMAPINFOHEADER lpBMIH)
{
return (int)(((ImageWidth() * NumPlanes() * BitCount() + 31) / 32) * 4);
}


That's probably why it looks different in the sizes. The bitmap class in itself actually has no problems that I can see. I ran a test program and loaded up 30 different bitmaps in my program and deleted them all with no errors. The problem occurs when I use two different size Animated Sprite images (in my CAnimSprite class) and then I go to free them.

Here is the definition of lpDIB which is the variable that basically stores the bitmap (or DIBs) information.
in CBitmap.h:
Code:
LPBYTE lpDIB;


Here is the first thing that gets called when I create a new CAnimSprite in my game program:
Code:
ogre = new CAnimSprite(hdc)


which calls the constructor of CAnimSprite. After it has been constructed then I declare the following:
Code:
if (!ogre->LoadAnimSeq(0, 3, 0, Game->GetPath(L"spidy.bmp"), 200, 200))
Game->FatalError(L"Error loading spidy.bmp")

In this example I load a picture of spiderman on the pocket pc in an animated sequence. It's kind of fun.

This calls the code in CAnimSprite.cpp LoadAnimSeq
Code:
BOOL CAnimSprite::LoadAnimSeq(int iStartCol, int iNumFrames, int iRow, LPTSTR lpFilename, int iWidth, int iHeight)
{
CBitmap *source;
int iStartX, iStartY, iFrame;

if (iStartCol < 0 || iNumFrames > NUM_FRAMES)
return FALSE;

if (iWidth < 1 || iWidth > 240 || iHeight < 1 || iHeight > 320)
return FALSE;

source = new CBitmap(GetScreenDC());
if (!source->Load(lpFilename))
{
delete source;
return FALSE;
}

for (iFrame = 0; iFrame < iNumFrames; iFrame++)
{
if (!sprites[iFrame]->Create(iWidth, iHeight))
{
delete source;
return FALSE;
}

iStartX = iStartCol * (iWidth + 1) + iFrame * (iWidth + 1);
iStartY = iRow * (iHeight + 1);

BitBlt(sprites[iFrame]->GetSourceDC(),
0, 0, iWidth, iHeight,
source->GetSourceDC(),
iStartX, iStartY, SRCCOPY);

iTotalFrames++;
}

SetFrame(iStartCol);
SetImageSize(iWidth, iHeight);
delete source;

return TRUE;
}


LoadAnimSeq calls Create in the CBitmap class:
Code:

//////////////////////////////////////////////////////////////////////
// CBitmap::Load
//
// Loads a bitmap file into a device context.
//
BOOL CBitmap::Load(LPTSTR lpFilename)
{
LPBYTE lpSourceBits;
HBITMAP hSourceBitmap;
DWORD dwSourceBitsSize;
LPBITMAPINFO lpSrcDIB;

SetFilename(lpFilename);
if (!LoadDIB(lpFilename))
return FALSE;

lpSrcDIB = (LPBITMAPINFO)lpDIB;

hSourceBitmap = CreateDIBSection(GetScreenDC(), lpSrcDIB, DIB_RGB_COLORS,
(void **)&lpSourceBits, NULL, 0);

//hSourceDC = CreateCompatibleDC(GetDC(NULL));
hSourceDC = CreateCompatibleDC(GetScreenDC());
dwSourceBitsSize = lpSrcDIB->bmiHeader.biHeight *
BytesPerLine(&(lpSrcDIB->bmiHeader));
memcpy(lpSourceBits, BitmapDataIndex((LPSTR)lpSrcDIB), dwSourceBitsSize);

SelectObject(hSourceDC, hSourceBitmap);

//store bitmap header into bmBitmap
GetObject(hSourceBitmap, sizeof(BITMAP), &bmBitmap);

DeleteObject(hSourceBitmap);

return TRUE;
}



Note: I can use 1 CAnimSprite image and delete and it will work fine. If I use a second CAnimSprite image then I get mixed results when I go through and delete. I hope that this will help further. I have looked at the memory addresses that are being allocated as well when the objects are created and deleted and they are both the same.

P.S.
(sorry about the long post!)[/code]
ramses · 14 Sep 2004, 19:47 UTC — oops
Sorry, here's the create function as well in CBitmap.cpp
Code:

//////////////////////////////////////////////////////////////////////
// CBitmap::Create
//
// Used to create a new memory device context.
//
BOOL CBitmap::Create(int Width, int Height)
{
HBITMAP hSourceBitmap;

hSourceDC = CreateCompatibleDC(GetScreenDC());
if (hSourceDC == NULL)
return FALSE;

hSourceBitmap = CreateCompatibleBitmap(GetScreenDC(), Width, Height);
if (hSourceBitmap == NULL)
return FALSE;

hOldBitmap = SelectBitmap(hSourceDC, hSourceBitmap);
if (hOldBitmap == NULL)
return FALSE;

DeleteObject(hSourceBitmap);
return TRUE;
}
ramses · 16 Sep 2004, 18:12 UTC — new finds
The author of the game book actually wrote me back on this issue (Jonathan Harbour) and mentioned to me that the code actually works fine on the pocket pc 2002 OS? and it is a Casseopia pocket pc that he developed these things on.

I've noticed one thing on my project. If I load two separate bitmap images I get the memory alignment error and I'm out of luck. If I combine everything into 1 BIG bitmap image, then I have no problems.
In order to put ALL of the images onto 1 bitmap will increase the size of the game drastically and in a way I do not want because that is very inefficient.

I ran the programs on a Dell Axim X3 and had the same results. The Arm processors with pocket pc 2003 actually have problems with data misalignment and are not handled by the hardware. So, I'm still stuck where I need to fix the code, however, at least I think I have narrowed it down.
ramses · 20 Sep 2004, 22:31 UTC — hp fix
I called up HP and sent in my unit due to some other errors that were happening on the pocket pc. It turns out that part of the reason why I was getting data misalignment errors was due to the main board. After they replaced the main board on the pocket pc it still gets a first-chance exception, but that is much easier to track down. Thanks for all the posts. When I find the error now, I'll post the fixes up.
ramses · 25 Sep 2004, 06:41 UTC — a final end!
After just a little bit more searching, I finally found a page that helped me solve the problem.

http://www.softpath.ie/windowsce/whitepapers.htm

I love the internet! I have been able to finally repair my library to a state that is useable and with the memory leaks solved. The final problem I believe is that there was an error in the equasions being used to calculate and reserve memory for the bitmap. The bitmaps in memory were also being freed right on top of one another causing the first chance exception. I hope to never have a problem like this ever again! I won't post the code up again since the site above pretty much walks you through the entire process of loading a bit map on CE the right way!

Thanks to all that have posted code and helped.