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;
}

Recommended Answers

All 5 Replies

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

According to 2003 C++ Specification this is legal. An array with no elements is created.

@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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.