Zitrax
Zitrax

Reputation: 20344

Cppcheck with microsoft compiler extensions

The code below uses the microsoft compiler extensions __try and __leave:

void f()
{
  char* a = nullptr;
  __try {
    a = (char*) malloc(10);
    if(!a) __leave;
    a[1];
  } __finally {}
}

Currently the code above gives the following warning:

(warning) Either the condition '!a' is redundant or there is possible null pointer dereference: a.

So the problem seem to be that cppcheck does not understand that __leave leaves the block if a is null. Replacing it by a 'return' cause the warning to go away.

Is it possible to make cppcheck understand this? The cppcheck manual states:

You can check non-standard code that includes various compiler extensions, inline assembly code, etc.

but I didn't find any further information about that.

Note, I am not looking for changing the code to make cppcheck happy but to make cppcheck understand the existing code.

Upvotes: 5

Views: 161

Answers (1)

Firewave
Firewave

Reputation: 411

Support for this was added in Cppcheck 2.15.0 - see https://trac.cppcheck.net/ticket/8434. You need to specify --library=windows though to be working properly.

Without any parameters it will only report the memory leak:

input.cpp:9:1: error: Memory leak: a [memleak]
}
^

But if you add --inconclusive you will get a false positive similar to the one in the question:

input.cpp:7:15: warning: inconclusive: If memory allocation fails, then there is a possible null pointer dereference: a [nullPointerOutOfMemory]
        (void)a[1];
              ^
input.cpp:5:38: note: Assuming allocation function fails
        a = static_cast<char*>(malloc(10));
                                     ^
input.cpp:5:31: note: Assignment 'a=static_cast<char*>(malloc(10))', assigned value is 0
        a = static_cast<char*>(malloc(10));
                              ^
input.cpp:7:15: note: Null pointer dereference
        (void)a[1];
              ^

If you add --debug-warnings --check-level=exhaustive (the latter is necessary because the following diagnostics is currently bound to it):

input.cpp:6:16: debug: valueFlowConditionExpressions bailout: Skipping function due to incomplete variable __leave [valueFlowBailoutIncompleteVar]
        if(!a) __leave;
               ^

Since __leave is defined in the windows.cfg library configuration you need to add --library=windows. With that parameter added the debug warning and the false positive are gone.

Upvotes: 0

Related Questions