【问题标题】:PVS Studio complaining about dangerous macro expressionPVS Studio 抱怨宏表达危险
【发布时间】:2018-03-09 22:10:09
【问题描述】:

PVS Studio 抱怨一种危险的表达方式。在以下代码 C++ 代码中,参数“msg”必须用括号括起来

#include <iostream>

#define X  ("X")
#define Y  ("Y")
#define Z  ("Z")

#define FRED(msg) msg << Z        // <<-- Warning from PVS Studio
#define WILMA(msg) X << FRED(msg)
#define BUDDY(msg) Y << FRED(msg)
int main()
{
    std::cout << WILMA(BUDDY("xxxxxx")) << std::endl;
    return 0;
}

来自 PVS Studio 的警告消息是

V1003 The macro 'FRED' is a dangerous expression. The parameter 'msg' must be surrounded by parentheses. sample_demo.cpp 7

遵循此工具的建议并添加括号: #包括

#define X  ("X")
#define Y  ("Y")
#define Z  ("Z")

#define FRED(msg) (msg) << Z
#define WILMA(msg) X << FRED(msg)
#define BUDDY(msg) Y << FRED(msg)
int main()
{
    std::cout << WILMA(BUDDY("xxxxxx")) << std::endl;
    return 0;
}

此更改似乎创建了无效代码。 VS2017的编译错误如下:

 error C2296: '<<': illegal, left operand has type 'const char [2]'
 error C2297 : '<<' : illegal, right operand has type 'const char [7]'

问题

我很确定 PVS Studio 的建议在这种特殊情况下是不正确的。我错过了一些明显的东西并且工具是正确的吗?非常感谢。

【问题讨论】:

标签: c++ visual-studio-2012 pvs-studio


【解决方案1】:

我认为这个警告针对的是算术表达式。例如,如果msg0xf &amp; 8,则省略括号可能会产生不同的结果,因为operator &lt;&lt; 的优先级高于&amp;

【讨论】:

    【解决方案2】:

    文档也提到了这一点。 V1003 诊断规则对未预处理的代码进行操作,并且分析器不知道将来如何使用此宏。诊断规则允许识别宏中可能导致不正确算术运算的错误。但有时它会失败。存在更精确的V733 诊断,但不幸的是,它可能会漏掉大量案例。

    引用的源代码导致误报,因为分析器认为'

    #define FRED(msg) (msg) << Z  //-V1003
    

    这是另一种选择。您可以使用这样的评论:

    //-V:<<:1003
    

    在这种情况下,使用“Suppression of false alarms 中提供了这些和其他抑制误报的方法的详细描述。

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 1970-01-01
      • 2017-11-05
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2021-12-01
      相关资源
      最近更新 更多