【问题标题】:How to check type safety in cppcheck or clang?如何在 cppcheck 或 clang 中检查类型安全?
【发布时间】:2015-09-26 04:43:33
【问题描述】:

我希望静态分析器警告我以下代码中的无效右值取消引用。如何在 clang 或 cppcheck 中做到这一点?

#include <memory>

using namespace std;

unique_ptr<int> myfunc(void)
{
    unique_ptr<int> a(new int(2));
    return a;
}


int main()
{
    const int& ra = *myfunc();
    return 0;   
}

【问题讨论】:

  • 这与类型安全无关。

标签: c++ clang type-safety cppcheck


【解决方案1】:

我是一名 Cppcheck 开发人员。

Cppcheck 有一个用于 std::string 的相关检查器。例如,您收到此代码的 Cppcheck 警告:

std::string hello();

unsigned int f() {
    const char *p = hello().c_str();
    return 0;
}

你得到的警告是:

[2.cpp:4]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.

报错是因为返回的std::string对象被立即删除。初始化后任何地方解引用指针p都是UB。

我认为最好也为您的 unique_ptr 代码提供警告。

如果您有兴趣.. 请随时帮助我们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2015-06-20
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多