Reputation: 965
I am writing a class that eventually will solve the 8-Queen puzzle. I added a test method named populate, to make sure i am creating the 2d array correctly and dynamically allocating memory correctly, however when this method is called the program crashes, when i debug the following Visual studio error pops up:
Exception thrown at 0x01281DFB in 8Queen.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.
If there is a handler for this exception, the program may be safely continued.
my constructor:
Queen::Queen(int s)
{
size = s;
board = new int *[size];
for (int i = 0; i < size; ++i)
board[size] = new int[size];
}
my populate method:
void Queen::populate()
{
for (int i = 0; i < size; ++i) // for each row
for (int j = 0; j < size; ++j) // for each column
board[i][j] = 1;
}
my deconstruct:
Queen::~Queen()
{
for (int i = 0; i < size; i++)
delete[] board[i];
delete[] board;
}
my main:
int main()
{
fm::Queen board(10);
board.populate();
board.printBoard();
return 0;
}
Upvotes: 0
Views: 32
Reputation: 1619
In your constructor, you have the following line:
board[size] = new int[size];
Likely, you want this to be
board[i] = new int[size];
Upvotes: 3