Jo - 2022-02-08

Latest cppcheck (2.7) complains about a redundant null pointer check. And it's actually correct. However, the redundancy is hidden inside a macro call. It is not unusual to have a general purpose macro (with additional safety checks) and there is little that can be done to avoid this redundancy when such macros are involved.

Please consider the following stripped down C code snippet I extracted from a real world program:

$ cat redundant.c 
#define SAFE_NAME(s) ((s) && (s)->name) ? (s)->name : ""

struct MyStruct {
    const char* name;
    enum { SOMETYPE };
};

void func(struct MyStruct** const sPtr)
{
    struct MyStruct* s = *sPtr;
    if (s->type == SOMETYPE) {
        printf("module %s\n", SAFE_NAME(s));
    }
}
$ cppcheck -q -f redundant.c --enable=style
redundant.c:11:9: warning: Either the condition 's' is redundant or there is possible null pointer dereference: s. [nullPointerRedundantCheck]
    if (s->type == SOMETYPE) {
        ^
redundant.c:12:24: note: Assuming that condition 's' is not redundant
 printf("module %s\n", SAFE_NAME(s));
                       ^
redundant.c:11:9: note: Null pointer dereference
    if (s->type == SOMETYPE) {
        ^