views:

261

answers:

2

I am writing a program that will read lines from an infile using getline into strings, convert the strings to c-strings containing the first m nonwhitespace characters of the string, then concatenate the c-strings into a single char array.

A sample file might look something like this:

5    //number of rows and columns in a grid
2    //number of grids
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

So I'd end up with a char array of 2x5x5 characters. Now the problem is my code works fine on smaller test cases like the one shown above, but segmentation faults when I try it on bigger grids (i.e. 100x100x100).

#include <iostream>
#include <string>
using namespace std;
int main(){
  int mapsize,levels;
  cin>>mapsize;
  cin>>levels;
  char map[mapsize*mapsize*levels];
  string input;
  for (int i=0;i<levels;i++){
    for (int j=0;j<mapsize;j++){
      getline(cin,input);
      char *row;
      row=new char[input.size()+1];
      strcpy(row, input.c_str());
      for (int k=0;k<mapsize;k++){
        map[i*mapsize*mapsize+j*mapsize+k]=row[k];
      }
      delete [] row;
    }
  }
return 0;
}

I'd call this program with an infile: ./program < infile.in

I've run it using gdb and did backtrace. It always points to the line "string input;"

Any ideas how I can resolve this segfault? Thanks

+7  A: 

map is a VLA, allocated on the stack, so I'd guess that your problem is that you get a stack overflow. gdb points a the construction of input because that's the first thing that gets constructed on this overflowed stack.

Éric Malenfant
Yup, 100*100*100 is a megabyte, the stack size on most machines. Use malloc() instead.
Hans Passant
thank you! this was very helpful.
zebraman
Funny that they'd name an error after this website.
Emile Cormier
+2  A: 

I am not sure why the backtrace is pointing to string input; but when you are copying row into map. if mapsize is bigger than the size of row, you could well end up seg-faulting. This will be more common for a bigger mapsize.

you also may well be stomping over return addresses on the stack that could be causing the "wrong" core-dump.

doron