Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ GDI+ Objects Memory leak/too many objects?

ive been making a c++ drawing program and i have a part where im drawing using gdi+ inside a function so i need to declare my graphics object every time i call the function.. this obviously is wrong and causes a leak somewhere so after some calls it gets slower and then suddenly stops drawing all together ,as expected.

im trying to clear my objects every time it finishes drawing but it doesnt seem to solve the issue. i thought maybe the PEN objects are part of the issue but some insight would be very helpful my code:

void function()
{
    DWORD pdwGduStartup;
    GdiplusStartupInput GdiStartupInp;
    GdiplusStartup(&pdwGduStartup, &GdiStartupInp, NULL);
    Pen pnPen_Blue(Gdiplus::Color(255, 0, 0, 255), 2.0F);
    Pen pnPen_Green(Gdiplus::Color(255, 255, 0, 255), 2.0F);


    LPCSTR LGameWindow = "MyWindow";
    HWND hGameWindow = FindWindow(NULL, LGameWindow);
    Graphics graphics(GetDC(hGameWindow));
for (int n=10; n>0; n--)
    graphics.DrawLine(&pnPen_Green,0, 0, 0, n);
    GdiplusShutdown(pdwGduStartup);
    graphics.Flush();
}

thanks alot!

edit: added release DC did not do anything!

DWORD pdwGduStartup;
GdiplusStartupInput GdiStartupInp;
GdiplusStartup(&pdwGduStartup, &GdiStartupInp, NULL);
Pen pnPen_Blue(Gdiplus::Color(255, 0, 0, 255), 2.0F);
Pen pnPen_Green(Gdiplus::Color(255, 255, 0, 255), 2.0F);


LPCSTR LGameWindow = "MyWindow";
HWND hGameWindow = FindWindow(NULL, LGameWindow);
HDC GDC = GetDC(hGameWindow);
Graphics graphics(GDC);
ReleaseDC(hGameWindow, GDC);
GdiplusShutdown(pdwGduStartup);
graphics.Flush();

My GDI objects still rises up to 10,000!

like image 238
tim_po Avatar asked Sep 12 '25 18:09

tim_po


2 Answers

GdiplusShutdown must be called after all GDI+ objects are removed. In your code Pen and Graphics destructors are called after GdiplusShutdown, when the objects go out of scope.

like image 61
Artem Razin Avatar answered Sep 15 '25 09:09

Artem Razin


I guess the problem is in GetDC. You should call ReleaseDC or use WTL smart pointers.

As I remember such things where easy to debug with task manager. It shows HANDLE count as well as GDI object count for a process, so you can see what lines generate new objects.

like image 30
Eugene Avatar answered Sep 15 '25 07:09

Eugene