C++: memory leaks
c++, memory-leaks, new-operator
Solution
It can cause them if a == 0 or a == 2.
If a == 1 an exception is thrown and no memory allocated. If a > 2 memory is both allocated and freed.
If a == 0 memory must be allocated since new is not allowed to return null pointers. You must free allocated memory with delete[].
If a == 2 memory is allocated and function returns. That's an obvious leak.
Problem
The question: At what value of variable n the following code will cause memory leaks? That's the code: ``` int* Bar(int n) { if (n == 1) throw "exception"; return new int[n]; } void Foo(int n) { int *a = Bar(n); if (n <= 2) return; delete[] a; } ``` - It's clear that if n is 2 there will be memory leaks. - If n is 0 there possibly will be memory leaks (acording to C++ new int[0] -- will it allocate memory?) From 5.3.4/7 When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements. From 3.7.3.1/2 The effect of dereferencing a pointer returned as a request for zero size is undefined. Also Even if the size of the space requested [by new] is zero, the request can fail. That means you can do it, but you can not legally (in a well defined manner across all platforms) dereference the memory that you get - you can only pass it to array delete - and you should delete it. Here is an interesting foot-note (i.e not a normative part of the standard, but included for expository puprposes) attached to the sentence from 3.7.3.1/2 [32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.] - And if n is 1 we get: int *a = Bar(1) and Bar(1) throws exception. Will it be the exception in constructor of variable a? And will it cause memory leaks?