after examineing this code, it seems like it actually allocates space for the pointer....but how? is this a bug? how can u allocate space for an array of 0 elements

int main()
{

int *ptr = new int[0];

return 0;
}

For a dynamically allocated array with new T[N] , N must be non-negative; it may evaluate to zero. When N is zero, an array with no elements is allocated and a distinct non-null pointer to it is returned. This array with no elements is deleted normally; with delete[]

@template
What happen when we create array dynamically?
=>It allocate the memory space for specified size if available and return the address of first block of memory to the pointer otherwise it return NULL.
If is it correct then memory for zero size array it should be return NULL i think, but when I try to execute this code on Turbo C++ compiler it gives some address.
Can any one Explain.

For a dynamically allocated array with new T[N] , N must be non-negative; it may evaluate to zero. When N is zero, an array with no elements is allocated and a distinct non-null pointer to it is returned. This array with no elements is deleted normally; with delete[]

If you read this again, this person explained that "a distinct non-null pointer...is returned". So you will get a memory address, since the array is still allocated space - it exists, just with no elements.

As your sample (int *ptr = new int[0]) demonstrates; an array of zero returns a valid pointer, not null. This is intentional since it’s specifically documented in the C++ standard.

Contrast this to malloc, where the return value under this condition is implementation depended.

I agree with you, it seems strange to allocate an array of zero bytes, which you cannot reference. But consider that when you do access an array you need to range check anyway.

Most likely this behavior is provided for generic programming/template support, where passing a zero size array may be needed.

Edited 5 Years Ago by template<>: n/a

This article has been dead for over six months. Start a new discussion instead.