数独求解器中的Segfault

时间:2014-11-26 02:01:47

标签: c++ segmentation-fault sudoku fault

我正在写一个数独求解器来练习下学期的技能。当我尝试运行它时,我遇到了分段错误。使用gdb,我跟踪它到这个代码函数:

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;
}

更具体地说,我认为错误发生在valids.push_back(val)行,但我不能为我的生活找出原因。也许我错过了一些显而易见的东西,但我只是不知道。有人可以提供一些指导吗?

1 个答案:

答案 0 :(得分:1)

看起来您可以从一些对阵列执行边界检查的额外代码中受益:

   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]++;
    }

您应该进行自己的错误处理,尤其是因为函数的参数可以包含任何值,尤其是数组范围之外的索引。