可能的空指针取消引用-否则将其检查为空是多余的 [英] Possible null pointer dereference - otherwise it is redundant to check it against null

查看:531
本文介绍了可能的空指针取消引用-否则将其检查为空是多余的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,这些代码正常工作:

I have the following code, which is working properly:

int result = ERRORCODE_OK;
if (dataObj == NULL || dataObj->inputSignal == NULL)
{
   result = ERRORCODE_MISSING_DATAOBJ;
}
if (result == ERRORCODE_OK && dataObj->spectrum == NULL) // CPP-Check error
{
   result = Calculate(dataObj->inputSignal, .. );
} 
return result;

但是CppCheck给我以下错误:

But CppCheck gives me the following error:

可能的空指针取消引用: dataObj -否则将其检查为空是多余的。

Possible null pointer dereference: dataObj - otherwise it is redundant to check it against null.

我不明白为什么。如果 dataobj NULL ,则结果将为 ERRORCODE_OK

I don't understand why. If the dataobj is NULL, then the result will be something else then ERRORCODE_OK.

推荐答案

CppCheck进行的检查不够深入,以至于您的第二个条件不能得到充分评估第一个成功:

CppCheck doesn't inspect deep enough to see that your second condition won't be fully evaluated if the first one succeeds:

int result = ERRORCODE_OK;
if (dataObj == NULL || dataObj->inputSignal == NULL)
    result = ERRORCODE_MISSING_DATAOBJ;

// Here, you can see that either dataObj!=NULL or result!=ERRORCODE_OK.
// But CppCheck can't!

if (result == ERRORCODE_OK && dataObj->spectrum == NULL)
    result = Calculate(dataObj->inputSignal, .. );
return result;

安抚检查器的三种替代方法显示出来。首先,只需在第二个 if 中重复检查 dataObj 是否为空。其次,将第二个 if 更改为 else if

Three alternative ways of pacifying the checker present themselves. Firstly, just repeat the check that dataObj is non-null in the second if. Secondly, change the second if to else if:

int result = ERRORCODE_OK;
if (dataObj == NULL || dataObj->inputSignal == NULL)
{
    result = ERRORCODE_MISSING_DATAOBJ;
}
else if (result == ERRORCODE_OK && dataObj->spectrum == NULL)
{
    result = Calculate(dataObj->inputSignal, .. );
} 
return result;

第三,一旦发现以下错误情况之一,请立即返回:

Thirdly, return as soon as you find one of the error cases:

if (!dataObj || !dataObj->inputSignal)
    return ERRORCODE_MISSING_DATAOBJ;
if (dataObj->spectrum)
    return ERRORCODE_OK;
return Calculate(dataObj->inputSignal, .. );

这篇关于可能的空指针取消引用-否则将其检查为空是多余的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆