简体   繁体   中英

Creating and using fonts / avoiding memory leaks in windows GDI

I'm trying to get to the bottom of a memory leak in an application written in C and running on Windows CE 6.0. I suspect that the issue MAY be related to the handling of the paint event of the window. In pseudo code it looks like this.

LRESULT CALLBACK HandlePaint(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) 
{
    HDC hdc;
    PAINTSTRUCT ps;
    hdc = BeginPaint (hWnd, &ps);

    HFONT logfont;
    FONTINFO font1, font2;

    memset(&logfont, 0, sizeof(LOGFONT));
    //set font options for font1.
    font1 = CreateFontIndirect(&logfont);

    memset(&logfont, 0, sizeof(LOGFONT));
    //set font options for font2.
    font2 = CreateFontIndirect(&logfont);

    for(int i = 0; i <= SOME_NUMBER; i++)
    {
        DrawStuff(hdc, font1);
        DrawStuff(hdc, font2);
    }   

    EndPaint (hWnd, &ps);

}

INT DrawStuff(HDC hdc, HFONT font)
{
    HPEN pen = CreatePen(PS_SOLID, borderWidth, bordercolor);
    HBRUSH brush = CreateSolidBrush(backcolor);

    SelectObject (hdc, pen);
    SelectObject (hdc, brush);
    SelectObject(hdc, font);

    SetTextColor (hdc, forecolor);
    SetBkColor (hdc, backcolor);
    DrawText (hdc, pChar, wcslen(pChar), prect, DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);

    DeleteObject(font);
    DeleteObject(brush);
    DeleteObject(pen);
}

I've noticed in the examples I've seen for windows graphics that there seems to be a pattern for most grapics objects of:

HBRUSH brush = CreateBrush();
SelectObject(hdc, brush);
// use brush
DeleteObject(brush);

However, as you can see in the example above with the fonts, each font is being created once, and then Selected/Deleted multiple times. I'm not sure what the implications are of doing that. Would there be a reason to suspect a memory leak here?

Thanks!

I agree with @pmg's comment that the creator of the Form should be the destroyer of the font, not the DrawStuff callee.

Also bear in mind that SelectObject returns the original item in the DC and you should always return that object when you're done, eg:

HPEN newPen = CreatePen(...);
HPEN oldPen = SelectObject(hdc, newPen);

// do stuff

// clean up
SelectObject(hdc, oldPen); // <-- note this line
DeleteObject(newPen);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM