Is this okay?

Started by
1 comment, last by frob 12 years, 10 months ago
Is it safe to allocate a zero size array? What about delete[]ing it?

A* a = new A[0];
delete[] a;

Advertisement
The 2005 Working Draft, Standard for Programming Language C++ states that

"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."
[section 5.3.4]

So, according to the standard, yes it should be safe. But the usual rules apply, so be sure to delete[] what you new[].

Is it safe to allocate a zero size array? What about delete[]ing it?

A* a = new A[0];
delete[] a;





You can request storage of zero bytes, just like you described above. It will attempt to allocate an array with no elements.


Yes you can do it, yes they exist in common code, such as empty container classes, and yes they are useful.

When you have an array with no elements there is nothing for you to dereference, that is, you cannot access a[0] because it is beyond the length of the array. There may still be some uses for it, such as a placeholder or marker or an empty container.

This topic is closed to new replies.

Advertisement