首页 > 解决方案 > 在 gcc/clang 中检测到这种未定义的行为?

问题描述

我正在尝试检测以下未定义的行为:

% cat undef.cxx
#include <iostream>

class C
{
    int I;
public:
    int getI() { return I; }
};

int main()
{
    C c;
    std::cout << c.getI() << std::endl;

    return 0;
}

由于某种原因,到目前为止,我所有的天真尝试都失败了:

% g++ -Wall -pedantic -o undef -fsanitize=undefined undef.cxx && ./undef
21971

同样适用于:

% clang++ -Weverything -o undef -fsanitize=undefined undef.cxx && ./undef
0

有没有办法在 gcc/clang 中使用魔法标志在编译时报告上述代码的警告/错误?在运行时?

参考:

% g++ --version
g++ (Debian 10.2.1-6) 10.2.1 20210110

% clang++ --version
Debian clang version 11.0.1-2

标签: c++g++undefined-behaviorclang++

解决方案


结果我的 g++ 版本似乎处理得很好,我所缺少的只是优化标志:

% g++ -O2 -Wall -pedantic -o undef -fsanitize=undefined undef.cxx  && ./undef
undef.cxx: In function ‘int main()’:
undef.cxx:7:25: warning: ‘c.C::I’ is used uninitialized in this function [-Wuninitialized]
    7 |     int getI() { return I; }
      |                         ^
0

这在上游有明确记录:

因为这些警告取决于优化,所以有警告的确切变量或元素取决于精确的优化选项和使用的 GCC 版本。

这是跟踪所有这些相关问题的上游“元”错误:


推荐阅读