问题
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.
回答1:
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.
回答2:
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.
回答3:
The latest version of Cppcheck 1.70 dev is able to detect this bug:
$ cppcheck test.cpp
Checking test.cpp...
[test.cpp:3]: (error) Array 'p[10]' accessed at index 100, which is out of bounds.
[test.cpp:4]: (error) Memory leak: p
来源:https://stackoverflow.com/questions/11966613/why-does-cppcheck-not-find-this-obvious-array-out-of-bounds-error