Search code examples
cgcc-warningstrdup

How to avoid "null argument where non-null required" compiler warning


Compiling the following code:

#include <string.h>
#define FOO (NULL)

int main(int argc, char *argv[])
{
    char *foo;

    if (FOO)
        foo = strdup(FOO);

    return 0;
}

results in the following compiler warning:

foo.c: In function ‘main’:
foo.c:9:3: warning: null argument where non-null required (argument 1) [-Wnonnull]
   foo = strdup(FOO);
   ^

However, strdup won't be called if FOO is NULL because of the if (FOO) check. Is there any way to avoid this warning?

Thanks!


Solution

  • If the idea is to assign a value to foo if FOO is defined, you could try:

    //#define FOO "lorem ipsum"
    
    int main()
    {
        char *foo;
        #ifdef FOO
            foo = strdup(FOO);
        #endif
    }
    

    It also has an advantage that the entire if code is not included when not needed.