Why GCC does not report uninitialized variable?

亡梦爱人 提交于 2020-01-24 03:23:26

问题


#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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/47307538/why-gcc-does-not-report-uninitialized-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!