https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101150
Bug ID: 101150 Summary: null pointer dereference false positive disappears when compiling an additional function Product: gcc Version: 11.1.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: adl at gnu dot org Target Milestone: --- Created attachment 51042 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=51042&action=edit source code, plus the three preprocessed versions I'm observing the following behavior with gcc-snapshot on Debian unstable as well as when using "x86-64 gcc (trunk)" and "x86-64 gcc (11.1)" on Godbolt. This false positive is not reported by gcc 10. % g++ --version | sed 1q g++ (Debian 20210527-1) 12.0.0 20210527 (experimental) [master revision 262e75d22c3:7bb6b9b2f47:9d3a953ec4d2695e9a6bfa5f22655e2aea47a973] % cat foo.cc #include <vector> #ifdef FOO void foo(const std::vector<int>& other) { std::vector<int> v; std::size_t sz = other.size(); v.resize(sz); int i = 0; for (int o: other) v[i++] = o; } #endif #ifdef BAR void bar(const std::vector<int>& other) { std::vector<int> v; unsigned sz = other.size(); v.resize(sz); int i = 0; for (int o: other) v[i++] = o; } #endif % g++ -O3 -Wnull-dereference -c foo.cc -DBAR % g++ -O3 -Wnull-dereference -c foo.cc -DFOO -DBAR % g++ -O3 -Wnull-dereference -c foo.cc -DFOO In function 'void foo(const std::vector<int>&)': cc1plus: warning: potential null pointer dereference [-Wnull-dereference] The two functions differ only by the type of sz, and the warning occurs only if foo() is compiled but bar() is not. I *believe* the warning comes from the fact that if sz is 0, the data pointer of v will still be nullptr after resize(), and that would render v[i++]=o invalid. However if sz is 0, the loop will not do any iteration, so that's a false positive. However I can't explain - why changing size_t into unsigned makes the warning go away, - why compiling the two functions makes the warning go away. I was expecting the diagnostics about foo() to be independent of the presence of bar(), and I was expecting to get the same diagnostics for both functions (preferably none, but I understand it's only a "potential" issue)