Josh Simani Josh Simani - 1 month ago 7
C++ Question

Segmentation fault: 11 (Sudoku Board)

When I try to display my sudoku board in my program, Terminal says:

Segmentation fault: 11


Here is a copy of my code:

#include <iostream>
using namespace std;

const int DIMEN = 9;

void generate_valid(int [][DIMEN]);
// generate a valid sudoku solution in a DIMENxDIMEN board

int main()
{
int valid_board[DIMEN][DIMEN];
// Declare the valid board array

generate_valid(valid_board);
// Initialize the board -- a valid solution

for (int i = 0; i < DIMEN; i++)
{
for (int j = 0; i < DIMEN; j++)
{
cout << valid_board[i][j];
cout << " ";
}
cout << endl;
}
return 0;
}

void generate_valid(int valid[][DIMEN])
{
// initialize the board array -- legit solution
for( int i = 0; i < DIMEN; i++ ) {
for( int j = 0; j < DIMEN; j++) {
// ROW ZERO: 0,1,2,...,9
if( i == 0 )
valid[i][j] = j % DIMEN + 1;
// ROWS 1 AND 2: 4,5,6... and 7,8,9...
else if( i == 1 || i == 2 )
valid[i][j] = (j + (i*3)) % (DIMEN) + 1;
// ROWS 3 AND 6: 2,3,4,... and 3,4,5,...
else if( i % 3 == 0 )
valid[i][j] = (j + (i/3) ) % DIMEN + 1;
// ROWS 4 AND 8: 5,6,7,... and 9,1,2,...
else if (i % 4 == 0 )
valid[i][j] = (j+i) % DIMEN + 1;
// ROW 5: 8,9,1...
else if( i == 5 )
valid[i][j] = (j+7) % DIMEN + 1;
// ROW 7: 6,7,8,...
else if( i == 7 )
valid[i][j] = (j+5) % DIMEN + 1;
}
}
}


What am I doing wrong? From what I've read on other posts about this error, this has to do with the program using an insanely large amount of memory, but this only uses 81 integers total on the sudoku board.

PRP PRP
Answer
for (int j = 0; i < DIMEN; j++)

Change this to :

for (int j = 0; j < DIMEN; j++)

Since j is being incremented un-restricted, valid_board[i][j] will access a memory location that does not belong to your program and hence a Segmentation Fault.

Comments