【发布时间】:2016-08-09 15:44:08
【问题描述】:
我遇到了分段错误,但我不确定在哪里
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;
};
不知道是不是代码的错误,可能我尝试分配一个空向量,但是向量读取的文件总是包含一些东西。
非常感谢。
【问题讨论】:
-
您的代码中哪里发生了异常?如果您不确定是否应该使用调试器遍历代码以找到它或使用 cout 语句以便知道您在代码中的位置。
-
向量应该被预先分配给一些数据量
-
您应该更加熟悉您的调试器。它比仅仅告诉你代码实际崩溃的库中的行更强大。
-
调试器说错误在 board[x][y].val = (uint) v.back();
-
你在哪里添加任何东西到
board?
标签: c++ vector segmentation-fault