user3521035
user3521035

Reputation: 23

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.

Upvotes: 2

Views: 1675

Answers (2)

Zebra North
Zebra North

Reputation: 11492

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.

Upvotes: 3

Floris Velleman
Floris Velleman

Reputation: 4888

You are already accessing the pointer before you check if it is valid: message_to_execute->code. Move this into the if statement and the warning will be gone.

CPPCheck is right, if it is a nullptr it will be a nullptr dereference and if it is not you will be checking if it is?

Upvotes: 2

Related Questions