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

Code runs on OSX, Segmentation fault in Codeblocks VMbox

所以当我 运行 在 OSX 中它工作正常时,但我的 class 需要它在使用代码块的 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;
}

您声明这些变量

int i, j, row, column

那你在这里做作业

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

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