Search code examples
objective-cmemory-leaksnibmacos-carbon

Can't get where is the memory leak in the function


I am having a problem in identifying a memory leak. I tried Instruments and it says that there is memory leak every time I call the function described below.

CFStringRef getStringFromLocalizedNIB(int cmdId)
{
    IBNibRef        nibRef;
    WindowRef       wind=NULL;
    CFStringRef     alertString;

    CreateNibReference(CFSTR("main"), &nibRef);
    CreateWindowFromNib(nibRef, CFSTR("Localized Strings"), &wind);
    DisposeNibReference(nibRef);

    ControlID   alertID = {'strn',cmdId};
    ControlRef  alertRef;
    GetControlByID(wind, &alertID,&alertRef);
    GetControlData(alertRef, kControlNoPart, kControlStaticTextCFStringTag, sizeof(CFStringRef), &alertString, NULL);
    return alertString;
}

Every time I call the function, I release the returned object.

CFStringRef lstr;
lstr = getStringFromLocalizedNIB(20);
//Use lstr;
CFRelease(lstr);

So can anybody please explain where the leak is?


Solution

  • If I understand correctly, you aren't showing the window created using CreateWindowFromNib(). I would expect the window to have the Carbon equivalent of release-on-close, and the CreateWindowFromNib() to be balanced by a ShowWindow(). I haven't done Carbon in 9 years though, so I'm not sure.

    Try calling DisposeWindow() on wind to balance the create:

        ...
        DisposeWindow(wind);
        return alertString;
    }