Dante - 9 months ago 34
C++ Question

# Runtime error when pushing to a vector of a vector

I've been having run-time errors with this program for a few days now, and have finally been able to find what the issue is: the

push_back
function is for some reason never completing, leading to a crash.

The Constructor is fine, the
stringstream
is fine (I've
cout
tested both of them), but anything after
vctr[i].push_back(Pixel(r,g,b);
does not run whatsoever. The program will immediately time out at that point.

Also, it does the same thing when trying directly assign values to the vector. Ex:
vctr[i][j] = Pixel(r,g,b);

Code in Question:

bool Picture::filetoVector(ifstream& fin, vector<vector<Pixel> >& vctr, int& cmax){
string line, filetype;
istringstream ssin;
int width, height, r, g, b;

//if fin fails to open file, return false & quite function.
if(fin.fail()) return false;

//This for loop grabs filetype, # of rows & columns (height & width), and cmax.
for(int i = 0; getline(fin,line) && i < 3;i++){....}

for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
getline(fin,line);
ssin.clear();
ssin.str(line);

ssin >> r >> g >> b;
//This is where things are breaking.
vctr[i].push_back(Pixel(r,g,b));
}
}
return true;
}


Pixel Class:

struct Pixel{
int red, green, blue;
Pixel();
Pixel(int r, int g, int b);
};


Pixel is very basic, containing only 3 integers and two Constructors. Pixel() sets red, green & blue to zero, Pixel(int r, int g, int b) sets red to r, green to g and so on.

filetoVector's call:

if(newpicture.filetoVector(filein, newvector, colorMax)){
cout << "Error: unable to read PPM file " << inputFilename;
return -1;
}


Welcome to StackOverflow Dante. You definitely did not post enough information to get a quick and smart answer here. You should post more code, specially:

• the one calling the function so that people can figure out how vctr is initialized.
• the Pixel class definition (does this one respect the rule of three? If not, pushing Pixel items to a vector is most likely unsafe)

I give it a try in "blind mode" anyway, you're most likely accessing vctr with an out-of-bound index when you do vctr[i]:

So you should simply do:

vctr.resize(height)


before your start the two nested for loops. To make sure there are height elements available in there...