In C++11 if we try to allocate array with negative size using global operator new, it will throw std::bad_array_new_length, but what about C++98 / C++03? Is it UB or will throw std::bad_alloc?
int main()
{
int* ptr = new int[-1];
}
The program is incorrect if the size is negative 5.3.4p6 from the C++03 standard:
Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value.
The above quote covers new T[a][b];
, where b
is the constant-expression according to the grammar and a
is the expression (only the first dimension).
You get this for int a[-1]
:
prog.cpp: In function ‘int main()’:
prog.cpp:4: error: size of array ‘b’ is negative
And this for int* a = new int[-1]
(runtime error):
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With