Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to delete char**

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?

like image 431
Eamonn McEvoy Avatar asked May 13 '11 09:05

Eamonn McEvoy


People also ask

How do I delete a char pointer?

1) You need to allocate room for n characters, where n is the number of characters in the string, plus the room for the trailing null byte. 2) You then changed the thread to point to a different string. So you have to use delete[] function for the variable you are created using new[] .

Do you need to delete char *?

Should it be delete or free when deallocating the memory used? Thanks! You delete (or delete[]) it when you longer need it and when it points to a char object that you created with new or new[]. You shouls delete/free only if it created with new/malloc, not if it is created on the stack.

How do you delete a char array in C++?

The code: char *p = new char[200]; p[100] = '\0'; delete[] p; is perfectly valid C++.

How delete [] is different from delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.


2 Answers

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.

like image 193
Oliver Charlesworth Avatar answered Oct 13 '22 11:10

Oliver Charlesworth


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() ;
like image 29
TonyK Avatar answered Oct 13 '22 11:10

TonyK