elena.bdc elena.bdc - 1 year ago 176
C++ Question

C++ Segmentation fault vector

I get a segmentation fault but I'm not sure where

The error produced in gdb states:

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

And here is the part of the code where the problem is, I suppose:

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 >> temp;
else if (c == '|') { //if input is |
in >> 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;
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


return v;

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

And tile.hpp

//Class tile
class tile {

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

I don't know is the error in the code, maybe I try to assign an empty vector, but the file read by the vector always contains something.

Thank you very much.

Answer Source

You don't initialize v. Also, where do you initialize board? Thirdly, how can you ensure v contains as many items as board?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download