c++ - visual studio 2013 静态代码分析——它的可靠性如何?

标签 c++ visual-studio-2012 visual-studio-2013 static-analysis

我正在尝试探索 VS 2013 中的静态代码分析选项。 我在下面写了非常简单的代码

int main()
{
    int a, b; //found unused variable 
    std::cout << "Hello world!";
    std::cin >> a;

    int* i = new int; // analysis didn't find this memory leak 
    //delete i;
    //i = NULL;
}

当我在上面的 block 上运行代码分析时,我希望它找到 int* i = new int; 并警告内存泄漏,但它没有找到但找到未使用的变量 b。

所以现在我有点困惑,内存泄漏是 C/C++ 中最常见的错误,而且这个工具找不到它。 现在我的问题是我们是否可以依赖此分析?

环境:Windows 7,VS 旗舰版 2013。

最佳答案

这不是 /analyze(又名 PREfast)旨在检测的那种代码问题。还有其他用于直接检测内存泄漏的常用工具,例如 CRT 调试堆——请参阅 MSDN .可以说,您应该首先使用像 std::unique_ptr 这样的 C++11 功能,永远不要 记住调用 delete

#include <memory>
int main()
{
    int a, b; //found unused variable 
    std::cout << "Hello world!";
    std::cin >> a;

    auto i = std::make_unique<int>()
}

/analyze 的目的是提供一些您从 lint 等产品中获得的“额外警告”,但主要是为了进行过程间缓冲区大小验证通过 SAL 注释。

这是它发现的错误类型:

void someFunction(char *buffer, size_t len)
{
    ...
}

void otherFunction()
{
    char buff[128];
    someFunction(buff, 256);
}

当您添加传达指针和大小之间关系的所需 SAL 时:

void someFunction(_Out_writes_(len) char *buffer, size_t len)

确实很难发现违反并导致缓冲区溢出的假设链,而不是内存泄漏。

/analyze 的另一个有用功能是验证可变长度 printf 参数与格式字符串:

void printf_debug( _In_z_ _Printf_format_string_ const char* format, ... )
{
    ...
}


void otherFunction()
{
    unsigned long l;
    std::wstring str;
    std::string str2;

    ...

    printf_debug( "%i %s %d", i, str.c_str(), str2.c_str());
}

VS 2015 and VS 2017 now include a few of the warnings that used to be only in /analyze in VS 2013 or earlier like shadowed variables and basic printf validation (if you write your own printf-style functions, you should still use /analyze with _Printf_format_string_). /analyze continues to provide SAL-based buffer analysis that is not part of the standard compiler.

/analyze PREFast 技术可以在某些情况下检测潜在的内存泄漏(特别是 C++ 异常安全)、潜在空指针的解引用、使用未初始化的内存等。它还有很多额外的功能处理内核模式编码和编写驱动程序的规则,特别是跟踪锁、IRQL 级别等。

Prefast And SAL Annotations

For C#, /analyze is the FXCop tool which is a code-analysis tool plus a 'style enforcer' for .NET.

关于c++ - visual studio 2013 静态代码分析——它的可靠性如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42179745/

相关文章:

c++ - STL 是 C++ 核心的一部分吗?

c++ - 如何为 Windows 安装 libjpeg?

c# - WPF 应用程序中图像文件夹的 URI

在 Visual Studio 2013 中创建混合应用程序时出现 Node.js 错误(找不到)

c++ - C++0x 中是否包含完整的 boost ?

c++ - 依赖于模板参数的成员函数实现

html - 在 ASP.net 中对齐文本

c++ - 在 MSVC 中压缩后可能发生数据损坏? (C++)

visual-studio - Visual Studio 2012 中未着色的类名

c# - 在 Visual Studio 内访问 Microsoft Azure