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

            Bug ID: 99851
           Summary: Warn about operator new that takes std::nothrow_t but
                    is potentially-throwing
           Product: gcc
           Version: 11.0
            Status: UNCONFIRMED
          Keywords: diagnostic
          Severity: enhancement
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redi at gcc dot gnu.org
            Blocks: 87403
  Target Milestone: ---

This program crashes with a segfault:

#include <new>

void* null() { return nullptr; }

struct X
{
  void* operator new[](std::size_t, const std::nothrow_t&) {
    return null();
  }

  unsigned data = 0;
};

int main()
{
  new(std::nothrow) X[2];
}

The problem is that the new overload is not noexcept, so the compiler assumes
it can't return null. The user probably intended it to be a non-throwing form
of operator new (as implied by the nothrow_t parameter), so we should warn that
it isn't noexcept.

N.B. if the function return nullptr directly then we warn:

new.C: In static member function ‘static void* X::operator new [](std::size_t,
const std::nothrow_t&)’:
new.C:6:12: warning: ‘operator new’ must not return NULL unless it is declared
‘throw()’ (or ‘-fcheck-new’ is in effect)
    6 |     return nullptr;
      |            ^~~~~~~

That should be updated to say 'noexcept' not 'throw()' and we might want the
two warnigns to use similar phrasing. That warning should also say "a null
pointer" not NULL.


Referenced Bugs:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87403
[Bug 87403] [Meta-bug] Issues that suggest a new warning

Reply via email to