Reputation: 672
There are some cases where potential unsigned integer overflows might cause issues. This example illustrates one:
struct Image
{
uint32_t width;
uint32_t height;
uint32_t depth;
};
void* allocateMemory(size_t);
...
allocateMemory(f.width * f.height * f.depth);
The x64 disassembly of GCC, clang and MSVC shows that the multiplications will be done using 32bit arithmetic. This might result into an overflow when there is a long list of multiplications.
mov eax, dword ptr [rdi + 4]
imul eax, dword ptr [rdi]
imul eax, dword ptr [rdi + 8]
mov rdi, rax
This godbolt link contains the above example and the disassembly of the 3 popular compilers: https://godbolt.org/z/1P1bT3jj6
I've enabled all possible warnings on GCC and clang (including -Weverything) but none reports issues in the above code. Only MSVC reported it inside the editor (C26451 Arithmetic overflow: Using operator * ...
) but I haven't managed to make it report that while building.
So the question is how to catch these types of issues when building the code (no runtime checks). Is there a static analysis tool that can catch this? Or maybe a way to have this Intellisense C26451
warning being reported when building with MSVC?
Upvotes: 2
Views: 143
Reputation: 51845
For MSVC, you can enable warnings such as C26451 while building by enabling "Code Analysis" in the project's (or file's) properties1:
Alternatively, you can run that code analysis on an open/active file at any time using the "Run Code Analysis on File" command from the "Build" menu (or Ctrl+Shift+Alt+f7).
You can enable this option on the command-line using the /analyze
switch; however, you will need to specify the code analysis "plugins" (which ship with Visual Studio) to use (a typical option would be along the lines of /analyze:plugin EspxEngine.dll
). An overview of these is given on this Microsoft web-page, in the "Analysis plugin options" section. The following paragraph appears particularly relevant:
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 But note, this option will increase build times considerably, which may become problematic for large projects.
Upvotes: 1