It's a shame for opinions about static code analyzers

Static code analysis tools have gone far ahead. These are not at all the "linters" that were actively used 20 years ago. However, many still refer to them as very simple tools. It's a shame. It's a shame both for the methodology of code analysis in general and for the PVS-Studio tool.







The reason for a little sadness was the comment on one of our articles. In this article, it was written that the analyzer detects a typo by issuing a warning to the following code:



if (A[0] == 0)
{
  X = Y;
  if (A[0] == 0)
    ....
}


The analyzer says that the second condition is always true. Indeed, if you examine the body of the function, it becomes clear that another element of the array should be checked.



On this, a comment was received approximately as follows:
Yes, the analyzer does indicate an error here. But in general, this warning is incorrect. After all, between two identical checks, the value of the element can change, and then the second check will make sense.
I'm sad. Programmers still think that code analyzers are built on regular expressions. Like, we found two identical nested if and swear.



Naturally, any modern static analyzer tracks changes in the value of variables. If the variable does not change, there will be a message. If it changes, there will be no message. For this, data flow analysis technology is used.



This is exactly what the PVS-Studio static analyzer does. Let's take a look at the following synthetic example:



char get();
int foo(char *p, bool arg)
{
    if (p[1] == 1)
    {
        if (arg)
            p[0] = get();
        if (p[1] == 1)          // Warning
            return 1;
    }
    if (p[2] == 2)
    {
        if (arg)
            p[2] = get();
        if (p[2] == 2)          // Ok
            return 2;
    }
    return 3;
}


The code contains two similar blocks. In one, the variable being checked does not change, and in the second it changes. Therefore, the analyzer issues a warning only for the first block: V547 Expression 'p [1] == 1' is always true.



Programmers need not worry. Modern tools are advanced and only issue warnings for really suspicious code. There are false positives, but, as a rule, they are associated with the presence of confusing code, which can be difficult even for a person to understand.





Additional links







If you want to share this article with an English-speaking audience, please use the translation link: Andrey Karpov. Upsetting Opinions about Static Analyzers .



All Articles