Search code examples
macrosexpandstatic-code-analysiscppcheck

cppcheck does not expand macro when checking C code?


I have code like below, and I use cppcheck to do static analysis. I found that it cannot report null pointer for data.

#define MY_FREE(p) if(p) {free(p);(p)=NULL;}

for(i=0; i<10; i++)
{
    ret = list_insert(list, data);
    if (1 != ret)
    {
        MY_FREE(data);
    }

    other_process(data->item);
}

But if I expand macro "MY_FREE" directly, it worked.

for(i=0; i<10; i++)
{
    ret = list_insert(list, data);
    if (1 != ret)
    {
        if(data) {free(data);(data)=NULL;};
    }

    other_process(data->item);
}

Is there any configuration can resolve it?


Solution

  • I am a Cppcheck developer. What is the exact code your testing? Cppcheck warns about this code:

    #define MY_FREE(p) if(p) {free(p);(p)=NULL;}
    
    void f() {
        struct Data *data;
        for(i=0; i<10; i++)
        {
            ret = list_insert(list, data);
            if (1 != ret)
            {
                 MY_FREE(data);
            }
            other_process(data->item);
        }
    }
    

    Reported warning:

    [1.c:12]: (warning) Possible null pointer dereference: data

    In your code.. it sounds like that we have false negatives for some reason.