我知道cppcheck可以检查变量上空指针的解引用。例如,这将触发cpp检查:
int* a = NULL;
*a = 5;有没有可能配置cppcheck,让它也验证函数返回的指针?如下所示:
int* foo() { return NULL; }
void main()
{
int a = *foo();
}而且,如果这是可能的,它也能在智能指针上工作吗?
发布于 2019-11-25 19:05:56
使用最新版本的Cppcheck (https://github.com/danmar/cppcheck/commit/e6d692d9605850cf98153a4825e353898b9320a2)运行您的示例,给出
$ g++ -c nullPointer.cpp && cppcheck --enable=all --inconclusive nullPointer.cpp
Checking nullPointer.cpp ...
nullPointer.cpp:4:14: error: Null pointer dereference: foo() [nullPointer]
int a = *foo();
^
nullPointer.cpp:2:0: style: The function 'f' is never used. [unusedFunction]
$ more nullPointer.cpp
int * foo(void) {return 0;}
int f(void)
{
int a = *foo();
return a;
}您使用的是什么版本?
更新:同时向Cppcheck单元测试套件添加了一个测试:https://github.com/danmar/cppcheck/commit/fd900ab8b249eec37df706f338c227f2a9adb3ef
更新2:关于智能指针:发现了智能指针的一些问题。例如,对于此C++代码:
#include <memory>
int main()
{
std::shared_ptr<int> p(nullptr);
int a = *p;
return a;
}Cppcheck发出一条错误消息:
./cppcheck fn_nullptr.cpp
Checking fn_nullptr.cpp ...
fn_nullptr.cpp:5:14: error: Null pointer dereference: p [nullPointer]
int a = *p;
^
fn_nullptr.cpp:4:28: note: Assignment 'p(nullptr)', assigned value is 0
std::shared_ptr<int> p(nullptr);
^
fn_nullptr.cpp:5:14: note: Null pointer dereference
int a = *p;
^但是通过智能指针返回空指针目前不会产生错误消息。现在有一个票证请求这样做:https://trac.cppcheck.net/ticket/9496
https://stackoverflow.com/questions/58981369
复制相似问题