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;
But CppCheck gives me the following error:
Possible null pointer dereference:
dataObj
- otherwise it is redundant to check it against null.
I don't understand why. If the dataobj
is NULL
, then the result will be something else then ERRORCODE_OK
.
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;
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, .. );