Luc Aux Luc Aux - 3 years ago 170
C++ Question

When should I use delete? (Consequences of not deleting after a dynamically created 2d array)

I am new to dynamic allocation and pointers. I will try to fill out a 2D dynamic array from a file and then apply a maze-solving algorithm (wall follower)on it.

Assuming I create a dynamically allocated 2D array like this:

int** board;
board = new int* [rowsize];

for(int row = 0; row < rowsize; row++)
{
board[row] = new int[colsize];
}


If I know that I won't be using this pointer for another variable, can I get away with not using delete for
board
? If not what could potentially go wrong (If you are familiar with the wall follower algorithm) ? Also how do I delete a pointer to a pointer, would
delete board
be sufficient?

Answer Source

can I get away with not using delete for board?

Yes, but not for very long: repeated failure to delete arrays that your program allocates is a memory leak that eventually runs your process out of memory.

how do I delete a pointer to a pointer, would delete board be sufficient?

No, you will need to delete each pointer that you allocated and stored inside board:

for(int row = 0; row < rowsize; row++) {
    delete[] board[row];
}
delete[] board;

Note square brackets after delete to indicate that you deleting an array, they are very important.

Allocating an deallocating memory for a rectangular matrix is a solved problem in C++ library. Switch to using a vector of vectors to avoid dynamic resource allocations:

std::vector<std::vector<int>> board(rowsize, std::vector<int>(colsize, 0));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download