Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why GCC does not report uninitialized variable?

#include <ios>
#include <iostream>
#include <map>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  map<int, int> v;
  int i;
  int t;
  while (cin >> i) {
    v[i] = t++;
  }
  auto mi = i;
  auto mt = t;
  for (const auto p : v) {
    if (p.second < mt) {
      mi = p.first;
      mt = p.second;
    }
  }
  cout << mi << '\n';
  return 0;
}

The abovementioned program makes heavy use of an uninitialized variable t, but GCC does not report it with -Wall or -Wuninitialized. Why is it so?

It is worth noting that Clang catches it:

main.cpp:13:12: warning: variable 't' is uninitialized when used here [-Wuninitialized]
    v[i] = t++;
           ^

Used g++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2).

Used clang version 4.0.1 (tags/RELEASE_401/final).


As you can see in https://godbolt.org/g/kmYMC1 GCC 7.2 does not report it even when it should. I will create a ticket in GCC's issue tracker.

like image 728
Bernardo Sulzbach Avatar asked Nov 15 '17 12:11

Bernardo Sulzbach


2 Answers

g++'s warning flag is not called -Wuninitialized: it is called -Wmaybe-uninitialized.

Also, as Jonathan Wakely noted in his answer, g++ is able to detect usage of uninitialized variables only when optimizations are enabled.

Enabling both -Wmaybe-initalized and optimizations produces the expected warning: https://godbolt.org/g/3CZ6kT

Note that -Wmaybe-initalized is enabled by default with both -Wall and -Wextra.

like image 195
Vittorio Romeo Avatar answered Oct 04 '22 19:10

Vittorio Romeo


GCC can only detect uninitialized variables when optimization is enabled, because the logic for tracking the values of variables is part of the optimization machinery.

If you compile with -O -Wall you get a warning:

<source>: In function 'int main()':
12 : <source>:12:13: warning: 't' may be used uninitialized in this function [-Wmaybe-uninitialized]
     v[i] = t++;
            ~^~
Compiler exited with result code 0

https://godbolt.org/g/327bsi

like image 23
Jonathan Wakely Avatar answered Oct 04 '22 20:10

Jonathan Wakely