Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator new with negative size

Tags:

c++

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];
}
like image 885
FrozenHeart Avatar asked Oct 23 '12 20:10

FrozenHeart


2 Answers

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).

like image 189
David Rodríguez - dribeas Avatar answered Sep 29 '22 23:09

David Rodríguez - dribeas


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
like image 42
alestanis Avatar answered Sep 30 '22 01:09

alestanis