c ++可能的空指针解引用 [英] c++ Possible null pointer dereference
问题描述
我对某些代码运行cppcheck以查找可能的运行时错误。并且它报告一个可能的空指针引用以下情况:
I ran cppcheck over some code to look for possible runtime errors. And it is reporting a possible null pointer dereference with the following situation:
Foo* x = ... //defined somewhere
...
Foo* y(x); //possible null pointer dereference.
编辑:更好的示例
for( int i = 0; i < N; i++ )
{
Foo* x( ArrayOfObjsContainingFooPtr[i].FooPtr ); // line 3
if( !x ) // line 4
continue;
}
来自cppcheck的错误讯息:
Error message from cppcheck:
[C:\file.cpp:3]:(错误)可能的null
指针dereference:x - 否则
是多余的, null at
第4行
[C:\file.cpp:3]: (error) Possible null pointer dereference: x - otherwise it is redundant to check if x is null at line 4
但我不知道这是可能的。
But I don't see how this is possible.
推荐答案
我真的很惊讶你得到了警告。对我来说,它的工作恰恰相反。使用从Linux中的源编译的cppcheck 1.46.1。这很好:
I am really surprised that you got that warning. For me, it works exactly the opposite. Using cppcheck 1.46.1 compiled from sources in Linux. This is fine:
struct Foo {
int x;
};
struct Obj {
Foo *FooPtr;
};
#define N 10
static Obj ArrayOfObjsContainingFooPtr[N];
int main() {
for( int i = 0; i < N; i++ ) {
Foo* x( ArrayOfObjsContainingFooPtr[i].FooPtr ); // line 3
if( !x ) // line 4
continue;
}
}
循环体它也是罚款根据cppcheck虽然它segfaults如果我实际上尝试运行它显然:
Now, with this loop body it is also "fine" according to cppcheck although it segfaults if I actually try to run it, obviously:
Foo* x( ArrayOfObjsContainingFooPtr[i].FooPtr ); // line 3
if (x->x == 0)
break;
if( !x ) // line 4
continue;
即使这是罚款:
int main() {
Foo *p = 0;
if (p->x == 0)
return 1;
这最终生成可能的空指针引用。可能,对:
And this finally generates "possible" null pointer dereference. Possible, right:
int main() {
Foo *p = 0;
p->x = 0;
有趣的是,这完全等同于前面的例子,可能)空指针引用:
The funny thing is that this, while being completely equivalent to an earlier example, gives definite (not "possible") null pointer dereference:
int main() {
Foo *p = 0;
if ((*p).x == 0)
return 1;
结论:cppcheck是一个真正的错误工具。
The conclusion: cppcheck is a really buggy tool.
这篇关于c ++可能的空指针解引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!