Search code examples
c++gccnew-operatorstatic-analysisnull-pointer

Why does GCC 11.1 warn about "use of possibly-NULL 'operator new(32)' where non-null expected"?


I am using GCC 11.1 and I have enabled the static analyzer with the option -fanalyzer. Now in this line:

    std::pair<NodeIterator, bool> result = idNodeMap.emplace(id,
            new Node(id, point));

I get the following warning:

..\src\Mesh\Mesh.cpp: In member function 'void Ct::Geometry::Mesh::addNode(int, const gp_Pnt&)':
..\src\Mesh\Mesh.cpp:30:43: warning: use of possibly-NULL 'operator new(32)' where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]
   30 |                         new Node(id, point));
      |                                           ^
  'void Ct::Geometry::Mesh::addNode(int, const gp_Pnt&)': events 1-2
    |
    |
In file included from ..\src\Mesh\Mesh.h:12,
                 from ..\src\Mesh\Mesh.cpp:9:
..\src\Mesh\Node.h:31:9: note: argument 'this' of 'Ct::Geometry::Node::Node(int, const gp_Pnt&)' must be non-null
   31 |         Node(int id, const gp_Pnt& point);
      |         ^~~~

Have I understood the warning correctly, that GCC wants me to check whether new returns null? According to this post: Will new return NULL in any case? this is never the case with current compilers and sound compilation options. So is this a warning for rare special cases and I should disable it?

Or have I overlooked something and there is a real danger in my code?


Solution

  • This is GCC bug #94355.

    Some work has been done, but the issue is still open and there's a comment in there with this specific issue.

    It sounds like it doesn't yet differentiate operator new that throws std::bad_alloc on allocation failure from (a hypothetical) one that returns nullptr.