New negative size operator

In C ++ 11, if we try to allocate an array with a negative size using the global operator new, it will call std :: bad_array_new_length, but what about C ++ 98 / C ++ 03? Is it UB or will it call std :: bad_alloc?

int main() { int* ptr = new int[-1]; } 
+5
c ++
source share
3 answers

The program is incorrect if the size is negative. 5.3.4p6 from the C ++ 03 standard:

Each constant expression in direct-new-declarator must be an integral constant expression (5.19) and evaluated with a strictly positive value . An expression in direct-new-declarator must be an integral or enumerated type (3.9.1) with a non-negative value .

The above quote covers new T[a][b]; , where b is a constant expression in accordance with the grammar, and a is an expression (only the first dimension).

+7
source share

the definition of new [] states that it requires an unsigned integer, also specified in size_t . So this should never compile.

See here http://en.cppreference.com/w/cpp/types/size_t (which is an unsigned int).

+2
source share

You will get this for int a[-1] :

 prog.cpp: In function 'int main()': prog.cpp:4: error: size of array 'b' is negative 

And this is for int* a = new int[-1] (runtime error):

 terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc 
0
source share

All Articles