14

I have a char**, basically an array of strings, that I need to delete. What is the correct way of doing this to ensure all pointers are cleared up?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Eamonn McEvoy
  • 8,876
  • 14
  • 53
  • 83

6 Answers6

22

The rule of thumb is that you need one delete (or delete[]) for each new (or new[]) that you issued.

So if you did:

char **pp = new char*[N];
for (i = 0; i < N; i++)
{
    pp[i] = new char[L];
}

then you will need to clean up with:

for (i = 0; i < N; i++)
{
    delete [] pp[i];
}
delete [] pp;

However, it should be noted that as you are in C++, you should probably be using std::vector<std::string> rather than arrays of arrays of raw char, because it would manage its own clean-up.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
9
char** StringList ;
int nStrings ;
....
for (int i = 0 ; i < nStrings ; i++)
  delete[] StringList[i] ;
delete[] StringList ;

Of course, it's simpler if you start with

std::vector<std::string> Stringlist ;

Then it's just

StringList.clear() ;
TonyK
  • 16,761
  • 4
  • 37
  • 72
  • 2
    Or `std::vector().swap(StringList)`, if you want to actually free *all* the memory. It's not leaked your way, but the vector's reserved space isn't freed until it's destroyed. – Steve Jessop May 13 '11 at 09:31
4

Do pattern matching as described below :

char *arr = new char[10];
char *p = new char;

delete [] arr;
delete p;

Did you see the pattern when to use what?

So now go to the original question:

char **dp = new char*[100]; //100 number of `char*`
for ( int i = 0  ; i < 100 ; i++ ) //loop for 100 times
    dp[i] = new char[30];  //allocate memory for each `char*`

 //deallocate
 for ( int i = 0  ; i < 100 ; i++ ) 
    delete [] dp[i]; //deallocate memory for each `char*`
 delete [] dp; //deallocate memory for `char**`
Nawaz
  • 353,942
  • 115
  • 666
  • 851
2
for(int i = 0; i < array_length; ++i)
{
    delete[] array[i]; // delete each entry in the array (assuming you used new[] for each string)
}

delete[] array; // delete the actual array.
Antony Woods
  • 4,415
  • 3
  • 26
  • 47
0

I assume that you have array like this:

char **pp = new char* [10];  // for the base pointer
for(int i = 0; i < 10; i++)
  pp[i] = new char[100]; // for every char* string

You should follow the reverse order. First clean up the member strings and then main pointer.

for(int i = 0; i < 10; i++)
  delete[] pp[i];
delete[] pp;
iammilind
  • 68,093
  • 33
  • 169
  • 336
0
for (int i = rows; i > 0; --i) {
 delete[] anArray[i-1];
}
delete[] anArray;
Jordonias
  • 5,778
  • 2
  • 21
  • 32