Segfault in sudoku solver

131 views Asked by At

I am writing a Sudoku solver to practice my skills for next semester. When I try to run it I get a segmentation fault. Using gdb, I track it to this code function:

vector<int> sudoku::valid_set(int row, int col)
{
    vector<int> valids;
    valids.push_back(0);

    int rows[9] = {0},
        cols[9] = {0},
        Grid[9] = {0};

    for (int i = 0; i < 9; i++)
    {
        if (i != col) 
        // we don't want to test the input cell because this 
        // will cause an incorect return
            rows[grid[row][i] - 1]++;
    }
    for (int i = 0; i < 9; i++)
    {
        // make sure current cell is not 0
        if (i != row) //we dont' want to test the input cell
            cols[grid[i][col] - 1]++;
    }
    // do the same steps for the mini grid using integer division 
    for (int i = row / 3 * 3; i < row / 3 * 4; i++)
    {
        for (int j = col / 3 * 3; i < col / 3 * 4; i++)
        {
            if (i != row && j != col)
                Grid[grid[i][j] - 1]++;
        }
    }
    // using the three arrays, find out what 
    // values need to go into the valids vector.  
    for (int i = 0; i < 9; i++)
    {
        if (rows[i] == 0 && cols[i] == 0 && Grid[i] == 0)
        {
            int val = i + 1;
            valids.push_back(val);
        }
    }
    return valids;
}

More specifically I think the error is occurring at the line valids.push_back(val) but I cannot for the life of me seem to figure out why. Maybe I am missing something blatantly obvious but I just do not know. Can anybody offer some guidance?

1

There are 1 answers

0
Thomas Matthews On BEST ANSWER

Looks like you could benefit from some extra code that performs boundary checks on your arrays:

   for (int i = 0; i < 9; i++)
    {
        if (i != col)
        {
           if (row >= MAXIMIM_ROWS)
               throw An_Error();
           int rows_index = grid[row][i];
           if (rows_index <= 0)
               throw Convulsions();

        // we don't want to test the input cell because this 
        // will cause an incorect return
            rows[grid[row][i] - 1]++;
    }

You should put in your own error handling, especially because parameters to the function could contain any value, especially indices outside the range of your arrays.