Stepan Stepan - 1 year ago 76
C++ Question

Deleting dynamic 2D array won't work

I have a problem with 2D dynamic array. Code is here:

char** arr = new char* [size];
for(int i = 0; i < size; i++)
arr[i] = new char[70];

It is basicly number of sentences with max 70 chars each. Ok... I used it before in that way.
Then I want to delocate it - I did it too!

for(int i = 0; i < size; i++)
delete [] arr[i];
delete [] arr;

And this will crash right at i = 0 with:
"Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)".

But as I said - I used it in different project in this way:

char** vety = new char* [pocVet];
for(int i = 0; i < pocVet; i++)
vety[i] = new char[100];
//Something (again a few sentences).
for(int i = 0; i < pocVet; i++)
delete [] vety[i];
delete [] vety;

I looked everywhere in here and it is the same. What is wrong?
PS: In the second example where it works don't mind different names (in my mother language).

Edit: Maybe it is because of the content of the array? But in the second case (where it works) are the sentences in it either. I just have a bunch of questions in it and user only choose the action - so basicly it is just sentences:

arr[0] = " 1 - Use something\n";
arr[1] = " 2 - Use different thing\n";
arr[2] = " 3 - etc...\n";
arr[3] = " 4 - etc\n";
arr[4] = " 5 - etc\n";
arr[5] = " 6 - etc\n";
arr[6] = " 7 - etc\n";

I do nothing with it... only printf();

Answer Source

You reassign the pointer arr[0] to point to a string literal.

arr[0] = " 1 - Use something\n";

So you leak the memory you allocated and then you try to call delete[] on memory you didn't allocate.

The solution is to not mess with raw pointers yourself, and instead use the standard library to do the difficult work for you.

std::vector<std::string> v;
v.emplace_back(" 1 - Use something\n");
// Other sentences
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download