In C++, every new must have a delete, otherwise a memory leak occurs. A memory leak is simply memory that was allocated but not deallocated after it's no longer used.
The problem with memory leaks is that the program wastes available memory, because it keeps allocating without deallocating.
I didn't know you were suppose to free a function parameter
Dynamically allocated things don't live inside functions.
In your example, newArr contains the memory address of a dynamically allocated array, but that dynamically allocated array doesn't deallocate automatically when the function returns.
Thus it makes sense to delete[] arr; because the allocated memory pointed to by arr doesn't care if the function that allocated it returned.
1 2 3 4 5 6 7 8 9
void f()
{
int *pi = newint[100];
}
int main()
{
f(); // memory leak, no delete[] anywhere!
}
Let's take an example, where the function is called repeatedly, many times.
I'm assuming here that the delete [] is not done.
Say the starting size is 1000 elements.
So initially that is the amount of memory in use.
Then the first time the function is called, it allocates 1001 elements. Total memory used is 2001 elements.
Call the function again, array size = 1002, memory used = 3002.
Call it 1000 times, the array has increased from original 1000 to now 2000.
But how much memory has been used? 1501500 elements have been allocated. That is, only 0.13% of the memory allocated is actually in use. The other 99.87% is lost - until the program ends.