Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Cppcheck not find this obvious array out-of-bounds error?

I installed the Cppcheck tool for static code analysis of my C++ project and got the feeling that it performs poorly. For example, can anyone tell me why Cppcheck is unable to find an array out-of-bounds error in the following code?

void f(int c) { 
    char *p = new char[10]; 
    p[c] = 42; 
} 

void g() { 
    f(100); 
} 

There's an online demo where this code can be conveniently checked using Cppcheck. All it comes up with is a memory leak at line 4, no signs of a potential buffer overflow.

like image 254
dokaspar Avatar asked Aug 15 '12 09:08

dokaspar


2 Answers

I am a Cppcheck developer.

It is not by design that Cppcheck fail to detect that.

Cppcheck currently doesn't evaluate functions using all given parameters from all function calls. We have tickets about this and I hope it will be fixed someday. It would be nice.

If you use Cppcheck you should not think that it will detect all bugs. Cppcheck will probably fail to detect most bugs. There is no method in my humble opinion that will detect all bugs in your software. Use Cppcheck just to detect some of the bugs that you fail to detect otherwise. It reduce the number of bugs somewhat.

I hope you are not too disappointed and will continue to use Cppcheck.

like image 84
Daniel Marjamäki Avatar answered Oct 15 '22 05:10

Daniel Marjamäki


Because it is not supported currently.

This is actually not an obvious error to the compiler. Something like

char c[5];
for (int i=0; i<10; ++i)
    c[i] = 0;

is more obvious, as it is all in the same code.

Something like

#define f(c) { \
    char *p = new char[10];  \
    p[c] = 42; \
}

void g() { 
    f(100); 
} 

is more obvious, because cppcheck and the compiler expand all macros in-place before actual checks.

However, your posted code is not trivial, because cppcheck as well as the compiler need the whole code inside that function and evaluate it with respect to the parameter. It is of course possible if the function is in sight (it becomes pretty hard, up to impossible, across translation units), but right now, cppcheck does not have that feature.

like image 9
Sebastian Mach Avatar answered Oct 15 '22 03:10

Sebastian Mach