This is similar to What does allocating a zero size array mean?
I have the following code
int *p = new int[0]; delete []p;
p gets the address and is deleted properly.
My question is: why is the allocation of null bytes allowed by the C ++ standard in the first place? Why doesn't he throw a bad_alloc or some special exception?
I think it just postpones a catastrophic failure, making life difficult for the programmer. Because, if the size to be allocated is calculated at runtime, and if the programmer correctly distributes it and tries to write something to this memory, it ends the memory corruption !!! and Crash could happen somewhere else in the code.
EDIT: How much memory does it allocate when requesting zero size?
c ++ memory-management
bjskishore123
source share