游戏开发论坛

 找回密码
 立即注册
搜索
查看: 2789|回复: 0

这个错误我查了一个晚上,不知道对大家有没有帮助

[复制链接]

12

主题

92

帖子

97

积分

注册会员

Rank: 2

积分
97
QQ
发表于 2003-10-24 22:19:00 | 显示全部楼层 |阅读模式
这是从本站的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帮忙!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2025-2-23 12:04

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表