https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109571

            Bug ID: 109571
           Summary: potential null pointer dereference
           Product: gcc
           Version: 12.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: f.heckenb...@fh-soft.de
  Target Milestone: ---

% cat test.cpp
#include <vector>

struct A
{
  int i = 0;
};

struct B: A
{
  virtual ~B ();
};

struct C
{
  std::vector <B *> v;
  virtual ~C () { for (A *a: v) a->i++; }
};

int main ()
{
  C c;
}
% gcc --std=c++20 -c -Wall -Wnull-dereference -O3 test.cpp 
test.cpp: In destructor ‘C::~C()’:
test.cpp:16:36: warning: potential null pointer dereference
[-Wnull-dereference]
   16 |   virtual ~C () { for (A *a: v) a->i++; }
      |                                 ~~~^
test.cpp:16:37: warning: potential null pointer dereference
[-Wnull-dereference]
   16 |   virtual ~C () { for (A *a: v) a->i++; }
      |                                 ~~~~^~
In destructor ‘virtual C::~C()’,
    inlined from ‘virtual C::~C()’ at test.cpp:16:41:
test.cpp:16:36: warning: potential null pointer dereference
[-Wnull-dereference]
   16 |   virtual ~C () { for (A *a: v) a->i++; }
      |                                 ~~~^
test.cpp:16:37: warning: potential null pointer dereference
[-Wnull-dereference]
   16 |   virtual ~C () { for (A *a: v) a->i++; }
      |                

Of course, strictly speaking any pointer dereference is *potentially* a null
pointer dereference, but there's no particular reason to assume one here. (In
fact, when making v private, the compiler could actually know that v will
always be empty, but still warns.)

Even more stragely, this warning depends on many factors that have nothing to
do with the elements by v being null or not, such as both the calling function
and some function in B being virtual, the for-loop variable being A* (not B*)
etc.

My actual code is of course more complex, so I'd like to understand what's
actually causing this warning, so I can avoid it. (Or should I just disable
it?)

And why is the same warning given 4 times?

Reply via email to