alepfu
alepfu

Reputation: 69

correct way to free up memory for an array of Objects containing an array of Objects in C++

I have something like this:

class HashTable
{  
  Bucket<E>** index;
  ...
}

 ~HashTable( ) 
 {
     delete[] index;
 }

 class Bucket
 {
    E* elements
    ...
 }

 ~Bucket( ) 
 {
     delete[] elements;
 }

How do I correctly free up the memory in this case?

Is delete[] index enough, or do I have to cycle throug all Bucket-Objects and delete elemtents-array seperatly?

Upvotes: 1

Views: 114

Answers (2)

jpalecek
jpalecek

Reputation: 47762

The HashTable contains a double array (I suppose), so it has to be deleted like this:

delete[] index[0];
delete[] index[1];
...
delete[] index;

If any of those levels are not arrays, but single pointers, you leave out the [].

The Bucket class, as you've written it, is fine, it will automatically delete its array and the E's in it.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206508

If you allocated each bucket object seperately using new you should deallocate each using delete.
The simple rule is:
You should have as many number of delete or delete[] as many new or new[] you have respectively.

Suggestion:
You might do yourself a favor by using smart pointers and saving yourself from such memory management problems.

Upvotes: 2

Related Questions