可能的空指针取消引用-否则将其检查为空是多余的
我有以下代码,这些代码正常工作:
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, .. );