memory allocation and 0 size: can I get the memory leaks?

c++, memory-leaks, new-operator

Solution

For C++11, and given your code:

int* a = new int[0];

Zero is a legal size, as per 5.3.4/7:

When the value of the expression in a noptr-new-declarator is zero, the allocation function is called to allocate an array with no elements.

The operator invoked is as per 18.6.1.2 (emphasis mine):

void* operator new[](std::size_t size);

...

3 Required behavior: Same as for operator new(std::size_t). This requirement is binding on a replacement version of this function.

4 Default behavior: Returns operator new(size).

...referencing 18.6.1.1...

void* operator new(std::size_t size);

3 Required behavior: Return a non-null pointer to suitably aligned storage (3.7.4), or else throw a bad_- alloc exception. This requirement is binding on a replacement version of this function.

So, the pointer returned must be non-null.

You do need to `delete[]` it afterwards.

Problem

My question are located in my code comment: ``` int* a = new int[0];// I've expected the nullptr according to my logic... bool is_nullptr = !a; // I got 'false' delete[] a; // Will I get the memory leaks, if I comment this row? ``` Thank you.

Original source

Related problems