cppcheck取消引用空指针



我知道cppcheck可以检查变量上空指针的取消引用。例如,这将触发cpp检查:

int* a = NULL;
*a = 5;

是否可以配置cppcheck,使其同时验证函数返回的指针?类似这样的东西:

int* foo() { return NULL; }
void main()
{
int a = *foo();
}

如果可能的话,它也适用于智能指针吗?

使用最新版本的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;
}

您使用的是什么版本?

更新:Cppchecks单元测试套件同时添加了一个测试: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

最新更新