jamesatha
jamesatha

Reputation: 7600

Proper way to delete an array of pointers

I have an array of pointers (that I created by calling new ptr*[size]). All of these pointers point to an object that was also put on the heap.

What is the proper way to delete the array and all new'd ptr's?

This is what I do now:

for (int i = 0; i < size; i++) delete array[i];
delete[] array; // Not sure since this double deletes array[0]

Does this do what I think it should?

Thanks

Upvotes: 3

Views: 7998

Answers (4)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

Yes, that does what you think it should. Since you did new for each element, you have to delete each element. And since you did new[] for the entire array, you need to delete[] the entire array.

As @djechlin rightly says in the comments, there's not really enough information to go on, but I'm presuming your prior code is something like this:

int** array = new int*[5];
for (int i = 0; i < 5; i++) {
  array[i] = new int;
}

Note that array is not actually an array type. It is a "pointer to pointer to int" and the array of pointers it points to was allocated with new[]. That's why you need to delete[] it.

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124632

Every pointer allocated with new gets a corresponding delete. Every pointer allocated with new [] gets a corresponding delete []. That's really all you need to know. Of course, when you have a dynamically allocated array which contains dynamically allocated pointers the deallocation must occur in reverse order.

So it follows that the correct idiom would be...

int main()
{
    int **container = new int*[n];
    for(int i = 0; i < n; ++i)
        container[i] = new int[size];

    // ... and to deallocate...
    for(int i = 0; i < n; ++i)
        delete [] container[i];

    delete [] container;
}

And then of course I say "stop doing that" and recommend you use a std::array or std::vector (and the template type would be unique_ptr<int>).

Upvotes: 12

evanmcdonnal
evanmcdonnal

Reputation: 48076

Yes. First you have to free the object each pointer in the array points to, then you have to free the array itself. In that order. If you reverse the order you'll have no reference to the objects and will leak a lot of memory.

Upvotes: 1

KCH
KCH

Reputation: 2844

Yes, first you delete each object to which elements of array point, and then you delete array of pointers itself. If you want to check your memory management, you can use tools like valgrind, they will be able to spot most errors.

Upvotes: 0

Related Questions