I'm trying to understand the use of delete[]. Will the following code have a memory leak?
int * getArray( )
{
int *r = new int[10];
for (int i = 0; i < 10; ++i)
r[i] = i;
return r;
}
int main ()
{
int *array;
for ( int i = 0; i < 10; i++ ) // main loop
array = getArray();
return 0;
}
The main loop seems to be allocating memory for 10 arrays, where only the last array has a valid pointer. If this is a memory leak, how do I free the memory storing the previous 9 arrays?
I can also compile using const int r[10];
in place of int *r = new int[10];
. Can the use of const
avoid a memory leak?