Why is import to use delete[] in this code?

Why is delete[] arr needed on line 8? I didn't know you were suppose to free a function parameter(even if it's a pointer O_o).

Thanks for any why can explain why it's a good choice to use delete[] on that pointer.

1
2
3
4
5
6
7
8
9
10
int* addElementToArray(const int* arr, const int currSize)
{
    int* newArr = new int[currSize + 1];
    for(int i = 0;i < currSize; i++)
    {
        newArr[i] = arr[i];
    }
    delete[] arr;
    return newArr;
}
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 = new int[100];
}

int main()
{
    f(); // memory leak, no delete[] anywhere!
}
Last edited on
To delocate memory back to the OS.

Aceix.
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.

Last edited on
Thank you guys I understand now.
Topic archived. No new replies allowed.