代码在OSX上运行,Codeblocks VMbox中的分段错误

时间:2015-06-18 12:55:25

标签: c++ segmentation-fault codeblocks

因此,当我在OSX中运行它时,它可以正常工作,但是我的类要求它使用Codeblocks在Xubuntu VMbox中工作。当我尝试在Codeblocks或VMbox的终端中运行它时,我收到错误“Segmentation fault(core dumped)”。这可能与需要导入不同的库有关吗?我想我以前遇到过这个问题。

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main(int argc, char const *argv[])
{
string filetoopen;
ifstream sudokutxtfile;
string txtline;
string sudokubox[9];
bool goodsudoku = true;
int i, j, row, column;

// Terminal input or default
if (argc == 2)
    filetoopen = argv[1];
else
    filetoopen = "sudokuboard.txt";
// Read in file, save to array, close file
sudokutxtfile.open(filetoopen);
while (getline(sudokutxtfile,txtline))
{
    sudokubox[row] = txtline;
    row++;
}
sudokutxtfile.close();
// Valid solution check
for (i = 0; i < 9; i++)
{
    for (j = 0; j < 9; j++)
    {
        // check whether sudokubox[i][j] is valid at the i's row
        for (column = 0; column < 9; column++)
            if (column != j && sudokubox[i][column] == sudokubox[i][j])
                goodsudoku = false;

        // check whether sudokubox[i][j] is valid at the j's column
        for (row = 0; row < 9; row++)
            if (row != i && sudokubox[row][j] == sudokubox[i][j])
                goodsudoku = false;

        // check whether sudokubox[i][j] is valid in the 3-by-3 box
        for (row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
            for (column = (j / 3) * 3; column < (j / 3) * 3 + 3; column++)
                if (row != i && column != j && sudokubox[row][column] == sudokubox[i][j])
                    goodsudoku = false;
    }
}
// Output 
if (goodsudoku == true)
    cout << "valid" << endl;
else
    cout << "invalid" << endl;
return 0;
}

1 个答案:

答案 0 :(得分:2)

您声明这些变量

int i, j, row, column

然后你在这里做作业

while (getline(sudokutxtfile,txtline))
{
    sudokubox[row] = txtline;
    row++;
}

row从未初始化,因此您尝试写入sudokubox[row]的任何索引都可能超出范围(或者是负数,或者颜色为绿色,或者谁知道什么)