C++ new int[0] -- will it allocate memory?


A simple test app:

cout << new int[0] << endl;



So it looks like it works. What does the standard say about this? Is it always legal to "allocate" empty block of memory?

7/6/2009 1:42:29 PM

Accepted Answer

From 5.3.4/7

When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.


The effect of dereferencing a pointer returned as a request for zero size is undefined.


Even if the size of the space requested [by new] is zero, the request can fail.

That means you can do it, but you can not legally (in a well defined manner across all platforms) dereference the memory that you get - you can only pass it to array delete - and you should delete it.

Here is an interesting foot-note (i.e not a normative part of the standard, but included for expository purposes) attached to the sentence from

[32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.]

8/31/2012 7:17:50 PM

Yes, it is legal to allocate a zero-sized array like this. But you must also delete it.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow