【问题标题】:cppcheck null pointer dereference: m_buffer - otherwise it is redundant to check it against nullcppcheck 空指针取消引用:m_buffer - 否则检查它是否为空是多余的
【发布时间】:2015-04-20 12:39:35
【问题描述】:

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

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

#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 - 否则检查它是否为空是多余的。

【问题讨论】:

  • 你已经有一个正确的answer,但是这个 DEBUG_LEVEL 东西似乎过于复杂并且容易出错。

标签: c++ cppcheck


【解决方案1】:

您在此处取消引用 message_to_executestd::clog &lt;&lt; "message with code : " &lt;&lt; message_to_execute-&gt;code

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢我解决了,但我正在处理其他类似的事情,我会发布它,如果无法删除错误,我会感谢你的想法
    • @user3521035 请将这个答案标记为已接受的答案,然后发布一个包含该特定场景的新问题(因为它可能是一个不同的问题)。 :)
    猜你喜欢
    • 2015-12-26
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多