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?
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[] .
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.
The code: char *p = new char[200]; p[100] = '\0'; delete[] p; is perfectly valid C++.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
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.
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() ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With