Mick
Mick

Reputation: 7937

Resource leak - too many device contexts

I have a (generally) working C++/Windows program which I noticed had a graphical resource leak. I the used GDIView and traced it to a build up of device contexts.

Looking further I tracked it to a pair of lines (see comments "Line A" & "Line B") as follows:

hdc = BeginPaint(hwnd,&global_paintstruct);

handle_of_source_device_context = CreateCompatibleDC(GetDC(0)); // Line A

#if 0 // temporarily while debugging
// stuff using handle_of_source_device_context
#endif

DeleteDC(handle_of_source_device_context); // Line B
EndPaint(hwnd,&global_paintstruct);

If I comment out lines A & B then there is no resource leak.

I tested that DeleteDC returns 1.

Any ideas?

Upvotes: 0

Views: 238

Answers (2)

Andrew Komiagin
Andrew Komiagin

Reputation: 6556

You need to call ReleaseDC for DC when it is no longer needed to prevent GDI leaks. The fixed version of your code will look like this:

hdc = BeginPaint(hwnd,&global_paintstruct);

HDC hWndDC = GetDC(NULL);
handle_of_source_device_context = CreateCompatibleDC(hWndDC); // Line A

#if 0 // temporarily while debugging
// stuff using handle_of_source_device_context
#endif

ReleaseDC(hWndDC);
ReleaseDC(handle_of_source_device_context);
DeleteDC(handle_of_source_device_context); // Line B
EndPaint(hwnd,&global_paintstruct);

Upvotes: 6

Jasper
Jasper

Reputation: 6556

Call ReleaseDC on the return value of GetDC:

dc = GetDC(0)
...
ReleaseDC(dc);

Upvotes: 2

Related Questions