What is the correct way to delete char**

Eamonn McEvoy picture Eamonn McEvoy · May 13, 2011 · Viewed 8.9k times · Source

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?

Answer

Oliver Charlesworth picture Oliver Charlesworth · May 13, 2011

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.