【问题标题】:Detect UB like Rust像 Rust 一样检测 UB
【发布时间】:2016-01-11 13:22:23
【问题描述】:

两个简化示例:

#include <cstdlib>
#include <string>
#include <vector>

class Object{};

void use1(Object * o)
{
    (void)(o);
}

void use2(std::string & s)
{
    (void)(s);
}

int f1()
{
    Object * object_ptr{ nullptr };
    {
        Object object{};
        object_ptr = &object;
    }
    use1(object_ptr); // UB
    return rand();
}

int f2()
{
    std::vector<std::string> v{"foo", "bar"};
    auto & v_ref = v[0];
    v.emplace_back("baz");
    use2(v_ref); // UB
    return rand();
}

int main()
{
    return f1() + f2();
}

rand() 仅用于测试。)

Rust 无法编译这样的源代码。使用 Clang 或 GCC(或者可能是 MSVC?)是否可以选择检测这种未定义的行为?

【问题讨论】:

  • rust 的类型有 lifetime,而 c++ 没有。
  • 如果您查看邮件列表,目前正在使用 clang 静态分析器进行生命周期检查:lists.llvm.org/pipermail/cfe-dev/2015-December/046653.html
  • @GuillaumeRacicot 仅检查可用工具:PVS-Studio 可以检测到第一个 UB (V506 Pointer to local variable 'object' is stored outside the scope of this variable. Such a pointer will become invalid.),但无法检测到第二个。 cppcheck 也可以先检测到(Dead pointer usage),但不能检测到第二个。

标签: c++ gcc clang undefined-behavior compiler-options


【解决方案1】:

开箱即用,不,你不能。 C++ 不像铁锈,它给了你自爆的力量。

幸运的是,静态分析器可以为您检测错误。使用 clang 静态分析器,生命周期检查器肯定正在开发中 link to the mailing list message 并且可能满足您的需求。

如果你有内存错误,你可以用 valgrind 检测它们,它对我来说有时很有用。

【讨论】:

  • 好吧,MSVCs (2013) 静态分析器没有发现这类错误,即使使用“所有规则”也是如此。
猜你喜欢
  • 2016-12-24
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2021-03-13
  • 2023-03-03
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
相关资源
最近更新 更多