识别潜在无符号整数溢出的警告(或其他方式)

Warnings (or other means) to identify potential unsigned integer overflows

在某些情况下,潜在的无符号整数溢出可能会导致问题。这个例子说明了一个:

struct Image
{
    uint32_t width;
    uint32_t height;
    uint32_t depth;
};

void* allocateMemory(size_t);

...

allocateMemory(f.width * f.height * f.depth);

GCC、clang 和 MSVC 的 x64 反汇编表明乘法将使用 32 位算法完成。当乘法列表很长时,这可能会导致溢出。

mov     eax, dword ptr [rdi + 4]
imul    eax, dword ptr [rdi]
imul    eax, dword ptr [rdi + 8]
mov     rdi, rax

这个godbolt link包含上面的例子和3个流行编译器的反汇编:https://godbolt.org/z/1P1bT3jj6

我已经在 GCC 和 clang(包括 -Weverything)上启用了所有可能的警告,但是 none 报告了上述代码中的问题。只有 MSVC 在编辑器中报告了它 (C26451 Arithmetic overflow: Using operator * ...),但我在构建时没能让它报告。

所以问题是如何在构建代码时捕获这些类型的问题(没有运行时检查)。是否有静态分析工具可以捕捉到这一点?或者也许是一种在使用 MSVC 构建时报告此 Intellisense C26451 警告的方法?

对于 MSVC,您可以通过在项目(或文件)属性1[=38 中启用“代码分析”来在构建时启用 C26451 等警告 =]:

或者,您可以运行在open/active文件随时使用“运行文件代码分析”进行代码分析" 来自“构建”菜单的命令(或 Ctrl+Shift+Alt+f7).


您可以使用 /analyze 开关在命令行上启用此选项;但是,您将需要指定要使用的代码分析“插件”(Visual Studio 附带)(典型的选项是 /analyze:plugin EspxEngine.dll)。 this Microsoft web-page 的“分析插件选项”部分给出了这些概述。以下段落似乎特别相关:

When you build on the command line, you can use the Esp.Extensions environment variable to specify EspXEngine extensions. For example:
set Esp.Extensions=ConcurrencyCheck.dll;CppCoreCheck.dll;


1 但请注意,此选项会显着增加构建时间 ,这对于大型项目可能会产生问题。