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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With