2
#include <iostream>
#include <new>

int main()
{
    int n = -1;
    try
    {
        int *p = new(std::nothrow) int[n];
        if(!p)
            std::cout << "new expression returned nullptr\n";
    }
    catch(const std::bad_array_new_length& e)
    {
        std::cout << "new expression threw " << e.what() << std::endl;
    }
}

Why does this code throw an exception? It prints new expression threw std::bad_array_new_length. According to the standard the new expression should return nullptr in this case.

If the expression in a noptr-new-declarator is present, it is implicitly converted to std::size_t. The expression is erroneous if:

— the expression is of non-class type and its value before converting to std::size_t is less than zero;

[...]

If the expression is erroneous after converting to std::size_t:

— if the expression is a core constant expression, the program is ill-formed;

— otherwise, an allocation function is not called; instead

— if the allocation function that would have been called has a non-throwing exception specification (14.5), the value of the new-expression is the null pointer value of the required result type;

— otherwise, the new-expression terminates by throwing an exception of a type that would match a handler (14.4) of type std::bad_array_new_length (17.6.3.2).

Compiled with gcc 9.2

Lassie
  • 853
  • 8
  • 18

1 Answers1

1

I suspect that this is a bug in libstdc++; running this code using clang and libc++ prints "new expression returned nullptr"

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
  • An error of libstdc++? Hardly, that's in the compiler proper. – Deduplicator Dec 19 '19 at 18:16
  • @Deduplicator - I don't think so. take a look at [the libc++ implementation](https://github.com/llvm/llvm-project/blob/master/libcxx/src/new.cpp#L112) – Marshall Clow Dec 19 '19 at 18:20
  • That shows that their nothrow op-new function properly swallows all exceptions. But one can no longer check for exceeded implementation-limit or negative input by then, that train has long ago left the station. Thus, it is irrelevant here. – Deduplicator Dec 19 '19 at 18:26
  • 1
    Yeah, this isn't a library issue. – T.C. Dec 19 '19 at 20:05