Search code examples
c++cppcheck

cppcheck null pointer dereference: m_buffer - otherwise it is redundant to check it against null


the code is working properly but when i checked it on cppcheck i found the null pointer dereferenc error i couldnt understand how to solve it. any thoughts would be appreciated

here is the part of code that i got the error

#ifdef DEBUG_LEVEL_MID
    std::clog << "STARTING FUNCTION int ConfigurationType::ExecuteMessageType()" << std::endl;
    std::clog << "message with code : " << message_to_execute->code << "will be tried o executed" << std::endl;
    #endif    

    if(!message_to_execute)
    {
        #ifdef DEBUG_LEVEL_ERROR
        std::cerr << "message_to_execute is null at: int ConfigurationType::ExecuteMessageType()" << std::endl;
        #endif    
        #ifdef DEBUG_LEVEL_MID
        std::clog << "message_to_execute is NULL at int ConfigurationType::ExecuteMessageType()" << std::endl;
        std::clog << "ENDING FUNCTION (0): int ConfigurationType::ExecuteMessageType()" << std::endl;
        #endif    
        return 0;
    }

the error is : Possible null pointer dereference: message_to_execute - otherwise it is redundant to check it against null.


Solution

  • You dereference message_to_execute here: std::clog << "message with code : " << message_to_execute->code.

    This means that the if (!message_to_execute) later is redundant because you are not allowed to dereference a null pointer, therefore the compiler is allowed to assume that message_to_execute is not null, and remove the test.