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