I have a grid class as follows. Using it in my program works fine until the main() function returns then there is an error message and the program crashes due to an uncaught exception. If I comment out the destructor the class works just fine. What would be the correct way to implement this destructor?
If I just delete[] grid
I assume that the arrays within it are not deallocated.
Exact error: Unhandled exception at 0x000869F5 in Battleship.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD.
class Grid
{
private:
int numRows;
int numCols;
char** grid; // array of arrays / pointer to pointer to char
public:
/*****************************************************************
Constructor()
*****************************************************************/
Grid() : numRows(0), numCols(0)
{
}
/*****************************************************************
Constructor(int, int)
*****************************************************************/
Grid(int numRows, int numCols) : numRows(numRows), numCols(numCols)
{
grid = new char*[numRows];
for (int arr = 0; arr < numRows; ++arr) {
grid[arr] = new char[numCols];
}
}
/*****************************************************************
Destructor NEEDS MAJOR EDIT AS IT IS CAUSING THE PROGRAM TO CRASH
*****************************************************************/
~Grid()
{
for (int i = 0; i < numRows; ++i)
{
delete[] grid[i]; //delete all subarrays of grid
}
delete[] grid; //delete grid
}
}