deallocating 2-dimensional dynamic array

here's what i've allocated
1
2
3
4
world = new char*[numRows];             //new array of char POINTERS
for (int i = 0; i < numRows; i++) {
    world[i] = new char[numColumns];
}

to delete this memory, do i just do this:
1
2
delete [] world;
world = 0;


or do i have to do this:
1
2
3
4
5
6
for (int i = 0; i < numRows; i++) {
    delete [] world[i];
    world[i] = 0;
}
delete [] world;
world = 0;


the latter is what i've got in my program now and it works, but if the former won't cause a memory leak and saves some primitive operations, i'd like to switch to it
Last edited on
The latter.

Every new needs a matching delete.

You don't need to zero the pointers if you're just going to delete them though:

1
2
3
4
5
6
for (int i = 0; i < numRows; i++) {
    delete [] world[i];
//    world[i] = 0;  // <- don't have to do this
}
delete [] world;  // <- because they won't exist anymore after this
world = 0;
thanks. but the pointers still exist, the address they hold just no longer belongs to the program. it's good practice (so i'm taught, but it makes sense) to set them to zero so nothing bad happens if they're accidentally dereferenced or delete is called on them again.

edit: oh wait, i see what you're saying. thanks
Last edited on
If the variable is local to a function or block, deleting variable doesn't actually affect.


Gorav
http://www.kgsepg.com
Topic archived. No new replies allowed.