CodeMonkey
CodeMonkey

Reputation: 4738

Clang Static Analyzer doesn't find the most basic problems

I wanted to try out the clang static analyzer. I'm on Windows and built clang with Visual Studio. It seems to work, but at the same time it seems to be extremely useless.

I made an example file

example.c

int main(void) 
{
    int h = 0;
    return 1/h;
}

Calling scan-build gcc -c example.c finds no error.

example.c

int main(void) 
{
    int h;
    return 1/h;
}

Calling scan-build gcc -c example.c finds no error.

example.c

int main(void) 
{
    return 1/0;
}

Calling scan-build gcc -c example.c finds no error.

If these most basic errors can't be found (and they can be found by clang itself), how can the static analyzer be of any use?

My gcc is MinGW if that matters. I also tried substituting clang but there's just nothing happening.

Am I doing something wrong here?

Upvotes: 9

Views: 3691

Answers (3)

DannyNiu
DannyNiu

Reputation: 1477

The scan-build driver substitutes an "interception" command in place of the compiler when doing analysis, so you need to make sure to use a "variable" as the name of the compiler.

For example, in POSIX shell: scan-build sh -c '${CC} "$@"' cc main.c -o main.

PowerShell may have similar syntax, but I'm not sure, DOS command line will need something radically different.

Upvotes: 2

MarkT
MarkT

Reputation: 21

be sure to use build-scan -v (verbose) to see if actually running clang checker. I followed this tutorial http://web.cs.ucla.edu/~tianyi.zhang/tutorial.html When I tried the C++ example it did not show any errors in the buggy code. The -v showed me that the provided Makefile was broken - after I fixed that clang still did not detect the bugs but g++ shows the bug.

Maybe they turned that particular check off. Clang Static Analyzer version 3.8 The tutorial uses version 3.2

Upvotes: 2

Ivan Kishchenko
Ivan Kishchenko

Reputation: 815

Maybe you are not doing something right. For example, the third example Visual Studio 2015 even refused to compile with error:

error C2124: divide or mod by zero.

I don't think Clang is not capable of detect something like that. However, this is not important.

I tried to check this code using PVS-Studio and it detected all three errors:

  • V609 Divide by zero. Denominator 'h' == 0. MFCApplication2 mainfrm.cpp 17
  • V614 Uninitialized variable 'h' used. MFCApplication2 mainfrm.cpp 23
  • V609 Divide by zero. Denominator '0' == 0. MFCApplication2 mainfrm.cpp 28

Therefore, I recommend you still experiment. At least the third case should be exactly found by Clang. A practical recommendation is to use more powerful tools, such as PVS-Studio, for analysis. He, by the way, finds errors in Clang and GCC.

Upvotes: 0

Related Questions