Possible dereferencing of a null pointer - otherwise it is redundant to check for null

I have the following code that works correctly:

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 tells me the following error:

Possible dereferencing of a null pointer: dataObj- otherwise, it is redundant to check it for null.

I do not understand why. If dataObj- NULLthen the result will be something else ERRORCODE_OK.

+4
source share
4 answers

CppCheck does not check deep enough to make sure that your second condition will not 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;

. -, , dataObj if. -, if 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;

-, , :

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

, NULL :

if (dataObj == NULL || dataObj->inputSignal == NULL)

, dataObj NULL.

Cppcheck , , result == ERRORCODE_OK dataObj != NULL, if. , , NULL , NULL .

, " ", .

+4

. null , , dataObj , , dataObj, , , ,

, . , , , .

+2

In general, this tool checks for NULL check statement, which hints to them that this object may be null, so after checking for null, if you try to reference it, an error will be displayed. It is good practice to return if something is wrong, if possible, or leave the link code out of reach. You can change your operators ifto achieve this or add returnto your first one if.

+1
source

Source: https://habr.com/ru/post/1609441/


All Articles