问题描述
我安装了工具来进行我的C ++项目的静态代码分析,并感到它的性能不佳。例如,任何人都可以告诉我为什么 Cppcheck在下列代码中无法找到数组超出错误?
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);
}
有一个,这里的代码可以方便地使用Cppcheck检查。所有它出现在第4行的内存泄漏,没有潜在的缓冲区溢出的迹象。
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.
推荐答案
目前支持。
这对编译器来说不是一个明显的错误。像
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.
像
#define f(c) { \
char *p = new char[10]; \
p[c] = 42; \
}
void g() {
f(100);
}
更为明显,因为cppcheck和编译器会先将所有宏展开实际检查。
is more obvious, because cppcheck and the compiler expand all macros in-place before actual checks.
然而,您发布的代码并不简单,因为cppcheck以及编译器需要在该函数内部的整个代码,并相对于参数进行评估。当然,如果函数是可见的(它变得相当困难,不可能,跨翻译单位),但现在,cppcheck没有那个功能。
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.
这篇关于为什么Cppcheck没有找到这个明显的数组超出界限的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!