Help in deallocation of memory. This .cpp has some errors which i cant figure out.

#include "connect.h"
# include <iostream>
# include <cstdlib>
using namespace std;


Connect::Connect()
{
grid = new int* [7];
for (int i =0; i<7 ; i++)
{
grid[i] = new int [7];
}
for (int i =0; i<7; i++)
{
for (int j =0; j<7; j++)
{
grid[i][j] = 0;
}
}
turn = (rand() % 2) + 1;

}
void Connect::display()
{
for (int i =0; i<7; i++)
{
for (int j =0; j<7; j++)
{
cout << grid[i][j] << " ";
}
cout << endl;
}

}
void Connect::switchTurn()
{
turn = 3- turn;
}
void Connect::setCell(int r, int c)
{
grid[r-1][c-1] = turn;
}
bool Connect::isFull()
{
for (int i =0; i< 7; i++)
{
for (int j=0; j<7; j++)
{
if(grid[i][j]==0)
{
return false;
}
}
}
return true;
}
bool Connect::won()
{
for (int col = 0; col <= 7; col++)
{
for (int row = 0; row <= 7; row++)
{
if ( grid[row][col] != 0)
{ //VERTICAL
if
( (grid[row][col] == grid[row + 1][col]) &&
(grid[row][col] == grid[row + 2][col]) &&
(grid[row][col] == grid[row + 3][col]) ||
//HORIZONTAL
( grid[row][col] == grid[row][col + 1]) &&
(grid[row][col] == grid[row][col + 2]) &&
(grid[row][col] == grid[row][col + 3]) ||
//RIGHT Diagonel
( (row - 3) >= 0 && (col + 3) < 7 ) &&
(grid[row][col] == grid[row - 1][col + 1]) &&
(grid[row][col] == grid[row - 2][col + 2]) &&
(grid[row][col] == grid[row - 3][col + 3]) ||

//LEFT Diagonel
( (col + 3) < 7 && (row + 3) < 7 ) &&
(grid[row][col] == grid[row][col]) &&
(grid[row][col] == grid[row + 2][col + 2]) &&
(grid[row][col] == grid[row + 3][col + 3]) ||
( (col + 3) < 7 && (row + 3) < 7 ) )
{
if (turn == 2)
{

winner = turn;
return true;
}
else
{
winner = turn;
return true;
}
}
}
}
}

return false;
}
void Connect::startGame()
{
while (1)
{
cout << endl;
cout << "Player " << turn << "'s" << " turn: ";
cin >> row;
cin >> col;
setCell (row, col);
display ();
if (won())
{
cout << "Player" << winner << "has won." << endl;
break;
}
if (isFull())
{
cout << "The game is Draw" << endl;
}
switchTurn();
}
}

Connect::~Connect(void)
{
if (grid!= NULL)
{
for( int i = 0 ; i < 7 ; i++ )
{
delete [] grid[i] ;
}
delete [] grid ;
}
}
Can't help without seeing connect.h

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
http://v2.cplusplus.com/articles/jEywvCM9/
It makes it easier to read your code and it also makes it easier to respond to your post.
Suspicious is:
1
2
3
for (int col = 0; col <= 7; col++)
{
for (int row = 0; row <= 7; row++)


versus:
1
2
3
for (int i =0; i<7; i++)
{
for (int j =0; j<7; j++)


ie <= versus <

So you have allocated storage for grid[7][7] (0 .. 6 by 0 .. 6) but accessed grid[8][8] (0 .. 7 by 0 .. 7). You should get memory access exceptions when you try to access the unallocated memory.
Last edited on
Topic archived. No new replies allowed.