Dangerous magic number N used

583 Views Asked by At

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?

3

There are 3 best solutions below

5
On BEST ANSWER

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.

3
On

Reading the link you posted, I concluded it is a false positive in your case.

The tool is assuming you are going to use n in a malloc (or equivalent allocation procedure) statement to be equivalent to the size of int (or any 4 bytes variable). So the recommendation is to use sizeof(desired type).

If you were using n inside a malloc statement, it would make sense - since int (or any other type) could vary for different architectures (if not now, in the future). But apparently this is not your case.

0
On

Number 4 is considered as one of the potentially dangerous numbers when porting from 32 bit to 64 bit hence warning on const being assigned 4. Other numbers are listed in the table behind the link you posted. With examples how it can be dangerous.

You can suppress individual warning by adding //-V112 at the end of line you are sure is 100% OK.

size_t const n = 4; //-V112

This will suppreess the warning and you can focus on your work again.

As for int a[4] = {}; PVS-Studio considers it a special case for which it doesn't issue warning. Why it doesn't take it into account in the first case I don't know. But it looks like hardcoded exception for really specific case.

If you are not building 64 bit builds, then I assume it is safe to disable the warning alltogether for now. But be warned - comes from sight comes from mind.