1

I have a dynamically allocated char** array as a private member in one of my classes.

The first allocation occurs according to number of words

client_interests = new char* [n];

Later each index of the array is allocated according to length of the word + 1

char[i] = new char [strlen(word)+1];

Would this be the proper way of deallocating the memory of this member (the classes dtor is calling this function)?

void Client::deallocate()
{
    int i;
    for (i = 0; i < n; i ++) //loops through each word
    {
        delete [] client_interests[i]; //each word is an array of characters, hence delete [] is used
    }
    delete [] client_interests; //deallocating the pointer
    client_interests = NULL;
}

Thaks!

Niall
  • 30,036
  • 10
  • 99
  • 142
Medvednic
  • 692
  • 3
  • 11
  • 28
  • 6
    Honestly, using a `std::vector` would be the most "proper" way of dealing with this outright. – WhozCraig Aug 18 '14 at 10:52
  • 2
    possible duplicate of [2-Dimensional array deallocation](http://stackoverflow.com/questions/10220322/2-dimensional-array-deallocation) – PrR3 Aug 18 '14 at 10:52
  • Yes, I know - but this is the assignment that was given to us, we have to use c type strings. – Medvednic Aug 18 '14 at 10:53
  • Your code seems not to have any errors, although `std::vector` is much much **much far** better solution. – ikh Aug 18 '14 at 11:00
  • You want to check whether `client_interests` is null before the loop; otherwise, calling the function a second time will do bad things with a null pointer. (Alternatively, do this work directly in the destructor, so there's no danger of calling it twice). Also, make sure you're following the [Rule of Three](http://stackoverflow.com/questions/4172722) (which standard containers would give you automatically). – Mike Seymour Aug 18 '14 at 11:25

3 Answers3

2

Yes, if you absolutely cannot use std::vector<std::string>, then your way of deallocating things is correct.

anderas
  • 5,744
  • 30
  • 49
2

Your code is correct. Since you allocate using new [], de-allocating with delete [] as you do is required. Also, obviously de-allocating in reverse order - inner arrays first, then outer array - is also required.

Jordan Samuels
  • 977
  • 6
  • 10
  • How about `for (i = n-1; i >= 0; --i)` if you *really* want reverse order? ;) – fredoverflow Aug 18 '14 at 11:08
  • @FredOverflow If you like, but it's not necessary and maybe not as readable. The reverse order need only apply to outer/inner, not to the individual inner allocations themselves, as they are independent. That said, if there are additional semantics and exception-safety concerns, it may be appropriate to do as you say. – Jordan Samuels Aug 18 '14 at 11:36
1

Yes this is the correct way of deallocating the 2d array.

delete []

is used to deallocate an array, and you are doing it correctly as you first deallocate the inner arrays and than the outer array.

Taimour
  • 459
  • 5
  • 21