new[0] Questions

1
2
3
4
5
6
7
8
9
10
11
#include <cstddef>

int main()
{
	volatile std::size_t zero = 0;
	char *p1 = new char[zero];
	char *p2 = new char[0];

	delete[] p1;
	delete[] p2;
}


1) Why does it compile without warnings?
2) Are the delete[]'s needed?
1) Do you expect warnings?
2) Yes
there's no reason why it shouldn't compile.

delete[] is necessary because arrays have another header (the number of lements for the destructor). If there's not destructor it might be the same(?)
Thanks for the answers.
I found a sister thread here: http://stackoverflow.com/questions/1087042/c-new-int0-will-it-allocate-memory

1) Do you expect warnings?

From the programmer's point of view, yes, for line 7.
But I'll go further than that, and say I'd like an exception thrown, in both cases.

From the standard expert's point of view, everything's fine I guess.

I'd love an example on how this Undefined Behavior-inducing trick is actually useful in practice.
According to that link
dereferencing a pointer returned as a request for zero size is undefined

As long as you don't dereference it, it would be fine. So you may avoid checks like in vector::vector(size_t)
Topic archived. No new replies allowed.