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