Menu

False positive memory leak on pointer used with XtAddCallback

2022-09-17
2022-09-19
  • Dusan Peterc

    Dusan Peterc - 2022-09-17

    I have the following code

    static void AddViewMenuItem(XnFileSelectionBox w, const char *name, int viewIndex) {
        Arg args[4];
        int n = 0;
    
        XmString label = XmStringCreateLocalized((char*)name);
    
        XtSetArg(args[n], XmNlabelString, label); n++;
        XtSetArg(args[1], XmNpositionIndex, w->fsb.selectedview == w->fsb.numviews ? 0 : w->fsb.numviews+1); n++;
        Widget item = XmCreatePushButton(w->fsb.viewMenu, "menuitem", args, n);
    
        if(viewIndex == 0) {
        w->fsb.viewSelectorList = item;
        } else if(viewIndex == 1) {
        w->fsb.viewSelectorDetail = item;
        }
    
        XtManageChild(item);
        XmStringFree(label);
    
        FSBViewSelection *data = malloc(sizeof(FSBViewSelection));
        data->fsb = w;
        data->index = viewIndex;
    
        XtAddCallback(
            item,
            XmNactivateCallback,
            (XtCallbackProc)SelectViewCallback,
            data);
        XtAddCallback(
            item,
            XmNdestroyCallback,
            (XtCallbackProc)SelectViewItemDestroy,
            data);
    }
    

    which, when tested with cppcheck 2.9 gets the error on last line of the function
    Fsb.c:2259:1: error: Memory leak: data [memleak]
    Apparently the data is allocated in the function, but not freed, as it is passed on as parameter to XtAddCallback().
    So "data" must not be freed, as it will be used in the future as a parameter of the callback.
    I call cppcheck with the following options
    --library=motif.cfg --platform=unix64 --std=c99 --enable=all

    The motif.cfg contains an entry for XtAddCallback:

    <function name="XtAddCallback">
    <leak-ignore>
    <returnvalue type="void">
    <arg nr="1">
    <not-uninit>
    </not-uninit></arg>
    <arg nr="2">
    <not-uninit>
    </not-uninit></arg>
    <arg nr="4">
    </arg></returnvalue></leak-ignore></function>
    So I am not sure if false positive is caused by bad definition in motif.cfg or by cppcheck itself.

    The code from the example is part of the open source Extended Motif FileSelectionBos
    https://sourceforge.net/projects/motifextfsb/

     
  • CHR

    CHR - 2022-09-18

    Shouldn't the data pointer still be saved somewhere so it can be free'd later?

     
    • Dusan Peterc

      Dusan Peterc - 2022-09-19

      It is saved in the callback, and SelectViewItemDestroy frees it.

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.