Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a compiler bug in MSVC++ 2017 update 3

#include <vector>

std::vector<int>::iterator foo();
void bar(void*) {}

int main()
{
    void* p;
    while (foo() != foo() && (p = 0, true))
    {
        bar(p);
    }
    return 0;
}

Results in error:

c:\users\jessepepper\source\repos\testcode\consoleapplication1\consoleapplication1.cpp(15): error C4703: potentially uninitialized local pointer variable 'p' used

like image 276
Jesse Pepper Avatar asked Dec 19 '22 00:12

Jesse Pepper


1 Answers

It's kind of a bug, but very typical for the kind of code you write.

First, this isn't an error, it's a warning. C4703 is a level 4 warning (meaning that it isn't even enabled by default). So in order to get it reported as an error (and thus interrupt compilation), compiler arguments or pragmas were passed to enable this warning and turn it into an error (/W4 and /Werror are the most likely I think).

Then there's a trade-off in the compiler. How complex should the data flow analysis be to determine whether a variable is actually uninitialized? Should it be interprocedural? The more complex it is, the slower the compiler gets (and because of the halting problem, the issue may be undecidable anyway). The simpler it is, the more false positives you get because the condition that guarantees initialization is too complex for the compiler to understand.

In this case, I suspect that the compiler's analysis works as follows: the assignment to p is behind a conditional (it only happens if foo() != foo()). The usage of p is also behind a conditional (it only happens if that complex and-expression is true). The compiler cannot establish a relationship between these conditions (the analysis is not complex enough to realize that foo() != foo() is a precondition to the entire while loop condition being true). Thus, the compiler errs on the side of assuming that the access could happen without prior initialization and emits the warning.

So it's an engineering trade-off. You could report the bug, but if you do, I suggest you supply a more compelling real-world example of idiomatic code to argue in favor of making the analysis more complex. Are you sure you can't restructure your original code to make it more approachable to the compiler, and more readable for humans at the same time?

like image 175
Sebastian Redl Avatar answered Dec 31 '22 18:12

Sebastian Redl