I am testing Clang Static Analyzer (CSA) on this code sample:
int main()
{
int* c = new int[10];
free(c);
int\* d = new int;
free\(d\);
int\* e = \(int\*\)malloc\(10\);
delete e;
}
For testing I have built clang from trunk and run analysis as
'./scan-build -k --use-analyzer=clang ./clang++ main.cpp'. Then I get
only one report about first bug:
main.cpp:11:14: warning: Memory allocated by 'new' should be
deallocated by 'delete', not free()
free(c);
^~~~~~~
1 warning generated.
scan-build: 1 bug found.
No information about errors on the next lines. When I comment first two
lines with bug, CSA is able to find next bug and so on.
Is there any workaround for this? Is it a bug? (at least for me for now
it looks like a bug)
Because behavior of the code that contains the first bug is undefined, Static Analyzer doesn't proceed to "execute" the rest of the program on that execution path - i.e., the program has already "crashed", it is irrelevant what happened next. It is tempting but dangerous to try to recover from the error because it is very likely that other bugs found on such execution path are false positives: after all, they happen only when the program already crashed. And if there's another execution path on which the other bug happens but the program doesn't crash, Static Analyzer would still find it when it explores the other path.
For example, in the following code all three bugs are found, because they occur on different execution paths:
extern bool coin();
int main()
{
if (coin()) {
int* c = new int[10];
free(c);
}
if (coin()) {
int* d = new int;
free(d);
}
if (coin()) {
int* e = (int*)malloc(10);
delete e;
}
}