[Bug analyzer/94355] support for C++ new expression

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Thu Jul 22 21:35:49 GMT 2021


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

--- Comment #9 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to William Navarre from comment #8)
> It seems that `operator new` is generally not supposed to return NULL --
> std::bad_alloc() is supposed to be thrown instead. 

If an operator new overload is declared noexcept, then it can return null on
failure. If it is not noexcept then it throws bad_alloc (or something derived
from it) and must never return null.


> 
> I made that change on my build (see below). I think that treating new's
> result as never-null is probably the correct thing to do most of the time,
> but two considerations: 
> 
> 1) The case of allocating a zero-length array. 

That still can't return null. It must return a valid non-null pointer, that
cannot be derefernced.

> 2) The case that a project has replaced `operator new.` (See "global
> replacements" at https://en.cppreference.com/w/cpp/memory/new/operator_new). 
> 
> Apparently projects can replace `operator new` (see "global replacements" at
> https://en.cppreference.com/w/cpp/memory/new/operator_new). It's not clear 

Exactly the same rules apply. If the operator new function is noexcept it
returns null to indicate allocation failure, otherwise it must throw and cannot
return null, ever.


More information about the Gcc-bugs mailing list