Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the allocation succeeds for size zero bytes?

This is similar to What does zero-sized array allocation do/mean?

I have following code

int *p = new int[0];
delete []p;

p gets an address and gets deleted properly.

My question is: Why allocation of zero bytes is allowed by c++ Standard in the first place? Why doesn't it throw bad_alloc or some special exception ?

I think, It is just postponing the catastrophic failure, making programmer's life difficult. Because if size to be allocated is calculated at run time and if programmer assumes its allocated properly and tries to write something to that memory, ends up corrupting memory !!! and Crash may happen some where else in the code.

EDIT: How much memory it allocates upon zero size request ?

like image 314
bjskishore123 Avatar asked Nov 09 '10 12:11

bjskishore123


2 Answers

Why would you want it to fail? If the programmer tries to read/write to non-existent elements, then that is an error. The initial allocation is not (this is no different to e.g. int *p = new int[1]; p[1] = 5;).

like image 64
Oliver Charlesworth Avatar answered Oct 21 '22 05:10

Oliver Charlesworth


3.7.3.1/2:

[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.]

Compare dynamically allocated array to std::vector for example. You can have a vector of size 0, so why not allow the same for the array? And it is always an error to access past the end of the array whether its size is 0 or not.

like image 38
vitaut Avatar answered Oct 21 '22 05:10

vitaut