Dante Dante - 1 year ago 53
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

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

The Constructor is fine, the
is fine (I've
tested both of them), but anything after
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++){....}

//This loop reads to vctr.
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){

ssin >> r >> g >> b;
//This is where things are breaking.
return true;

Pixel Class:

struct Pixel{
int red, green, blue;
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;

Answer Source

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:


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

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