|
这是从本站的ARTICLES->游 戏 基 础->游戏编程起源(初学者)Ⅵ
中抄下来稍加修改的错误函数,存在内存泄漏!我是WIN 的初学者,
不知道文章中的函数是不是也存在这个问题,我想应该是,因为问题不是存在我改动的地方,所以请搬用这个函数的兄弟们小心!
//*pbitmap paramate is the file name of bitmap file to load.
int ShowBitmap(HDC hDestDC,char *pbitmap, int xDest, int yDest,DWORD dwRop)
{
HDC hSrcDC; // source DC - memory device context
HBITMAP hbitmap; // handle to the bitmap resource
BITMAP bmp;
int nHeight, nWidth; // bitmap dimensions
if ((hbitmap = (HBITMAP)LoadImage(NULL,"bg.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE)) == NULL)
{
MessageBox(hMainWnd,"malloc ram failed!","failed",MB_OK);
return(FALSE);
}
else
{
}
if ((hSrcDC = CreateCompatibleDC(NULL)) == NULL)
{
return(FALSE);
}
if (SelectObject(hSrcDC, hbitmap) == NULL)
{
return(FALSE);
}
if (GetObject(hbitmap, sizeof(BITMAP), &bmp) == 0)
{
return(FALSE);
}
nWidth = bmp.bmWidth;
nHeight = bmp.bmHeight;
// copy image from one DC to the other
if (BitBlt(hDestDC, xDest, yDest, nWidth, nHeight, hSrcDC, 0, 0, dwRop) == NULL)
{
return(FALSE);
}
// kill the memory DC
DeleteDC(hSrcDC);
// return success!
return(TRUE);
}
下面是我找到错误后修改正确后的函数。
int ShowBitmap(HDC hDestDC,char *pbitmap, int xDest, int yDest,DWORD dwRop)
{
HDC hSrcDC; // source DC - memory device context
HBITMAP hbitmap; // handle to the bitmap resource
BITMAP *bmp=new BITMAP;
int nHeight, nWidth; // bitmap dimensions
if ((hbitmap = (HBITMAP)LoadImage(NULL,"bg.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE)) == NULL)
{
MessageBox(hMainWnd,"malloc ram failed!","failed",MB_OK);
return(FALSE);
}
else
{
}
if ((hSrcDC = CreateCompatibleDC(NULL)) == NULL)
{
return(FALSE);
}
if (SelectObject(hSrcDC, hbitmap) == NULL)
{
return(FALSE);
}
if (GetObject(hbitmap, sizeof(BITMAP), bmp) == 0)
{
return(FALSE);
}
nWidth = bmp->bmWidth;
nHeight = bmp->bmHeight;
// copy image from one DC to the other
if (BitBlt(hDestDC, xDest, yDest, nWidth, nHeight, hSrcDC, 0, 0, dwRop) == NULL)
{
return(FALSE);
}
// kill the memory DC
DeleteDC(hSrcDC);
DeleteObject(hbitmap);
delete bmp;
bmp=NULL;
// return success!
return(TRUE);
}
上一个函数有两个内存泄漏点,一个是调用LoadImage(),没有用DeleteObject(HGDIOBJ hObject);释放,另一个是使用BITMAP的地址直接调用,隐含隐指针没有释放.不知道是不是这样(如果使用局部变量的地址会这样吗?).呵呵,初学者,也不是很懂,还请前辈指点一二.
最后感谢Sea_bug帮忙!
|
|