GetDC()内存泄露

最近碰到的问题,在定时器中重绘图像发现了内存泄露稳定,反复测试发现是调用了GetDC函数导致的。我用的是visual studio 2010。上网一搜果然发现了问题。

http://blog.csdn.net/onlyou930/article/details/5902670

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

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

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);
    }

 

你可能感兴趣的:(GetDC()内存泄露)