Search code examples
cpointerssonarqubestatic-code-analysiscppcheck

Either the condition is redundant or there is possible null pointer dereference


I wrote a C code for an embedded system and when I execute the code analysis with SonarQube and CppCheck plugin I get this bug:

Either the condition is redundant or there is possible null pointer dereference: pointer.

This is the code that has the bug:

ReturnCode_e SocketTcpSecureWrite( SocketHandle_t socketHandle, 
                                   char* dataBuffer, 
                                   uint16_t dataBufferLen, uint16_t* byteTransmitted )
{
    uint32_t bytes = 0;
    ReturnCode_e opResult = SSL_WRITE_ERROR;

    *byteTransmitted = 0;

    if( dataBuffer == NULL || byteTransmitted == NULL )
    {
        return WRONG_PARAMETER;
    }

    if( SEND_SOCKET( socketHandle, dataBuffer, dataBufferLen, 0, &bytes ) == SUCCESS )
    {
        *byteTransmitted = bytes;
        opResult = SUCCESS;
    }

    return opResult;
}

I don't understand why the pointer consistency check appears as a bug. I want to verify that the pointer is not NULL before execute the function, otherwise I return an error.

Is this the right way to check the pointer consistency?


Solution

  • I looked through the code and checked it, immediately using PVS-Studio and it also issued a warning:

    V595: The 'byteTransmitted' pointer was utilized before it was verified against nullptr. Check lines: 39, 41. consoleapplication1.cpp 39

    Indeed, let's look at this code fragment:

    *byteTransmitted = 0;
    
    if( dataBuffer == NULL || byteTransmitted == NULL )
    

    In the beginning the pointer byteTransmitted is dereferenced, and only after that it is verified against NULL. It is an error. So, it is right that all analyzers complain about it. It will be correct firstly to verify and only then use the pointer:

    if( dataBuffer == NULL || byteTransmitted == NULL )
    {
      return WRONG_PARAMETER;
    }
    
    *byteTransmitted = 0;