C ++分段故障向量

时间:2016-08-09 15:44:08

标签: c++ vector segmentation-fault

我遇到了分段错误,但我不知道在哪里

gdb中产生的错误说明:

Program received signal SIGSEGV, Segmentation fault.
0x0000000100003c03 in std::__1::vector<tile, std::__1::allocator<tile> >::operator[] (this=0x0, __n=0)
at /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/vector:1497
1497        return this->__begin_[__n];
(gdb) where
#0  0x0000000100003c03 in std::__1::vector<tile, std::__1::allocator<tile> >::operator[] (this=0x0, __n=0)
at /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/vector:1497
#1  g2048::resume (this=0x7fff5fbff990) at ./game.hpp:430

以下是问题代码的一部分,我想:

std::vector<std::vector<tile> > board;

vector<int> readIntoVector() {
    char c;
    int temp;
    bool nonum;
    vector<int> v;

    ifstream in("save_game.txt", ios::in);

    if (!in.is_open()) cout << "Unable to open file" << endl;
    nonum = false;
    in >> sscore;

    while(in.good()) {
        in >> c;

        if (isdigit(c)) { //if the input is a number
            nonum = false;
            in.putback(c);
            in >> temp;
            v.push_back(temp);
        }
        else if (c == '|') { //if input is |
            in >> c;
            in.putback(c);
            if (isdigit(c)) nonum = false; //if next character is a number, don't add a 0
            else nonum = true; //if is not a number, add a zero
        }
        else if (c == '#') { //Case for 0 in the first position of the grid in each line
            in >> c;
            in.putback(c);
            if (c == '|') //if next character is |, means there's no number, so add 0
                nonum = true;
            else nonum = false;
        }
        else nonum = false;

        if (nonum)
            v.push_back(0); //add 0 in the vector
    }

    in.close();

    return v;
}

void resume() {
    cout << "In resume" << endl;
    vector<int> v = readIntoVector();
    cout << "Printing normal vector: ";
    Print(v);
    std::reverse(v.begin(), v.end());
    cout << "Printing reverse vector: ";
    Print(v);
    for (int y = 0; y < size; ++y)
        for (int x = 0; x < size; ++x) {
            board[x][y].val = (uint) v.back();
            v.pop_back();
        }
    score = sscore;
}

并且tile.hpp

//Class tile
class tile {

public:
    tile() : val( 0 ), blocked( false ) {}
    uint val;
    bool blocked;
};

我不知道代码中的错误,也许我尝试分配一个空向量,但向量读取的文件总是包含一些内容。

非常感谢。

1 个答案:

答案 0 :(得分:0)

您没有初始化v。另外,您在哪里初始化board?第三,如何确保v包含与board一样多的项目?