现在的位置: 首页 > 综合 > 正文

GetDC() ReleaseDC()引起的内存泄漏

2013年10月01日 ⁄ 综合 ⁄ 共 813字 ⁄ 字号 评论关闭

BUG: GetDC() ReleaseDC()引起的内存泄漏

     今天同事在一个定时器中画图,结果发现内存缓慢增长,怀疑是内存泄漏,查了很久,该释放的GDI资源都释放了的啊,可是还是无法解决,最后把GetDC()放在初始化里面,退出时调用ReleaseDC(),中间处理部分直接使用pDC,内存倒是不增长了,可是一直心里觉得奇怪,又仔细查了下,原来这是MFC的一个BUG.每次调用有4字节的内存泄漏,具体可见下面链接:
 

Steps to Reproduce the Behavior

In a method that is a part of a class that is derived from CWnd, insert the following code in your application:

CDC *pDC;
    RECT rect;

    GetClientRect (&rect);

    for (int i = 0; i < 1000; i++)
    {
        pDC = GetDC ();
        ReleaseDC (pDC);
  }

If you run this code and then check the system memory before and after you run the code, you notice that the system memory leaks four bytes per iteration. If you change the code to the following code, the memory leak does not occur:

HDC hDC;
       RECT rect;
    ::GetClientRect (m_hWnd, &rect);

    for (int i = 0; i < 1000; i++)
    {
        hDC = ::GetDC (m_hWnd);
        ::DrawText (hDC, L"Testing...", 10, &rect, DT_CENTER);
        ::ReleaseDC (m_hWnd, hDC);
    }
  

抱歉!评论已关闭.