new(std::nothrow) int[n] throws an exception

519 views Asked by At
#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

1

There are 1 answers

4
Marshall Clow On

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