条件是多余的,或者可能存在空指针取消引用

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

我为嵌入式系统编写了 C 代码,当我使用 SonarQube 和 CppCheck 插件执行代码分析时,我遇到了这个错误:

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

这是有错误的代码:

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;
}

我不明白为什么指针一致性检查会显示为错误。 我想在执行函数之前验证指针不为 NULL,否则我 return 一个错误。

这是检查指针一致性的正确方法吗?

我看了一下代码,检查了一下,马上用PVS-Studio,它也发出了警告:

V595: 'byteTransmitted' 指针在针对 nullptr 进行验证之前已被使用。检查行:39、41。consoleapplication1.cpp 39

确实,让我们看一下这段代码片段:

*byteTransmitted = 0;

if( dataBuffer == NULL || byteTransmitted == NULL )

一开始指针 byteTransmitted 被解除引用,然后才根据 NULL 进行验证。这是一个错误。所以,所有的分析员都抱怨它是正确的。先验证正确再使用指针:

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

*byteTransmitted = 0;