2

代码工作正常,但是当我在 cppcheck 上检查它时,我发现空指针 dereferenc 错误我无法理解如何解决它。任何想法将不胜感激

这是我收到错误的代码部分

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

错误是:可能的空指针取消引用:message_to_execute - 否则检查它是否为空是多余的。

4

2 回答 2

3

你在这里取消引用message_to_executestd::clog << "message with code : " << message_to_execute->code.

这意味着if (!message_to_execute)后者是多余的,因为不允许取消引用空指针,因此允许编译器假定它message_to_execute不为空,并删除测试。

于 2015-04-20T12:44:58.837 回答
2

在检查指针是否有效之前,您已经在访问指针:message_to_execute->code。将其移动到 if 语句中,警告将消失。

CPPCheck 是对的,如果它是一个 nullptr 它将是一个 nullptr 取消引用,如果不是,你将检查它是否是?

于 2015-04-20T12:41:46.740 回答