Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 425
Andrey Bushman Avatar asked Jul 02 '13 07:07

Andrey Bushman


People also ask

What causes a memory leak?

A memory leak starts when a program requests a chunk of memory from the operating system for itself and its data. As a program operates, it sometimes needs more memory and makes an additional request.

How do you find memory leaks?

To find a memory leak, you've got to look at the system's RAM usage. This can be accomplished in Windows by using the Resource Monitor. In Windows 11/10/8.1: Press Windows+R to open the Run dialog; enter "resmon" and click OK.

What happens if you do not free memory allocated?

It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default garbage value.


1 Answers

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.

like image 161
Tony Delroy Avatar answered Sep 18 '22 05:09

Tony Delroy