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

--- Comment #14 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to David Malcolm from comment #13)
> (In reply to Jonathan Wakely from comment #10)
> 
> [...snip...]
> 
> > As already noted above, new can't return null here, and there is no
> > dereference anyway. And the pointer isn't leaked, but it seems maybe the
> > analyzer doesn't know about destructors?
> 
> FWIW the analyzer (presumably incorrectly) considers the case where operator
> new returns NULL, and then attempts to write 0 to it.

Yeah, that's incorrect, the write is guaranteed to be OK because if new fails
it throws an exception before the write ever happens.

If a non-throwing form of new is used, e.g. p = new(std::nothrow) int(), then
the compiler *does* insert a null check before writing to it. So in the case
where a null check is necessary, the compiler inserts one.

See the -fcheck-new option:

  Check that the pointer returned by "operator new" is non-null before
attempting to modify the storage allocated.  This check is normally unnecessary
because the C++ standard specifies that "operator new" only returns 0 if it is
declared "throw()", in which case the compiler always checks the return value
even without this option.  In all other cases, when "operator new" has a
non-empty exception specification, memory exhaustion is signalled by throwing
"std::bad_alloc".  See also new (nothrow).

Reply via email to