Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangerous magic number N used

PVS-Studio, the static code analyzer, for the following bit of code

size_t const n = 4;
int a[n] = {};

reports:

V112 Dangerous magic number 4 used: ...t const n = 4;. test.cpp 3

Although PVS-Studio is used with Visual Studio 2017 project and reports the same warning for both, 32 and 64 bit, those build configurations are not taken into account by the analyzer, AFAIU.

I would have expected the context to be analysed better and treat the code above as equivalent to this

int a[4] = {};

for which PVS-Studio does not issue any diagnostics.

In the case above is this dangerous magic number N used, a false positive?

What are the reasons the two code samples above are not analyzed as equivalent?

like image 934
mloskot Avatar asked Jul 19 '17 15:07

mloskot


1 Answers

This

size_t const n = 4;
int a[n] = {};

is false positive.

64-bit diagnostics are very noisy and there is nothing you can do about it. Yes, the analyzer produces many false positives such as magic numbers like 4, 0xFFFFFFFF, etc. In the analyzer a lot of exceptions has already been made when it doesn’t complain (for example: int a[4] = {};). However, there are still so many options of using constants that it’s impossible to foresee all of them.

When porting code to 64-bit system it makes sense to look through all the magic numbers, to make sure that the programmer, for example, does not expect that the pointer size is 4 bytes somewhere. Then it makes sense to switch off V112 diagnostic so that it does not bother you.

like image 98
AndreyKarpov Avatar answered Sep 30 '22 12:09

AndreyKarpov