A simple test app:
cout << new int[0] << endl;
outputs:
0x876c0b8
So it looks like it works. What does the standard say about this? Is it always legal to "allocate" empty block of memory?
A simple test app:
cout << new int[0] << endl;
outputs:
0x876c0b8
So it looks like it works. What does the standard say about this? Is it always legal to "allocate" empty block of memory?
Every object has a unique identity, i.e. a unique address, which implies a non-zero length (the actual amount of memory will be silently increased, if you ask for zero bytes).
If you allocated more than one of these objects then you'd find they have different addresses.
Yes it is completely legal to allocate a
0
sized block withnew
. You simply can't do anything useful with it since there is no valid data for you to access.int[0] = 5;
is illegal.However, I believe that the standard allows for things like
malloc(0)
to returnNULL
.You will still need to
delete []
whatever pointer you get back from the allocation as well.Yes, it is legal to allocate a zero-sized array like this. But you must also delete it.
I found Effective C++ Third Edition said like this in "Item 51: Adhere to convention when writing new and delete".
From 5.3.4/7
From 3.7.3.1/2
Also
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 3.7.3.1/2