-3

I am trying to write a function that returns an array of struct in c++. I seem to be able to fill the array from an input file. However, I run into segmentation fault upon returning the struct array. Am I missing something?

Coordinates* GetCoordinates(string Input) {
        Coordinates* coor_array = new Coordinates[1000];
        int k = -1;

        string line;

        ifstream file;
        file.open(Input.c_str());

        while (!file.eof()){
                getline(file,line);
                k++;
                char** holder = split (line,' ');
                coor_array[k].element = holder[0];
                coor_array[k].x = atof(holder[1]);
                coor_array[k].y = atof(holder[2]);
                coor_array[k].z = atof(holder[3]);

                cout << "Atom:" << coor_array[k].element  << " X:" << coor_array[k].x << " Y:" << coor_array[k].y << " Z:" << coor_array[k].z <<endl;

        }
        return coor_array;
}

While my struct definition is below:

struct Coordinates
{
        string element;
        double x,y,z;
};

I use the following to call my function:

Coordinates* coor_data = GetCoordinates(Input);

Upon running, I get the following error:

 Atom:H X:26.4706 Y:30.0098 Z:64.4696
 Atom:O X:25.8063 Y:28.7746 Z:64.7809
 Atom:H X:25.6821 Y:30.626 Z:63.3106
 Segmentation fault

Could anyone suggest what could be the problem?

Astronomer
  • 109
  • 4
  • 3
    Don't. Use `std::vector` (if size is not known) or `std::array` (if size is known). Also see: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – NathanOliver Jul 27 '17 at 15:28
  • 1
    https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – UKMonkey Jul 27 '17 at 15:33
  • You have got a problem in the code we can't see (probably `split`). This is why we ask for a [mcve]. My guess is that you are mismanaging the return value from `split`. – Martin Bonner supports Monica Jul 27 '17 at 15:34
  • I added how I call the function in main, which might complete the missing code. I don't think split is the problem since I have tested thoroughly. – Astronomer Jul 27 '17 at 15:40
  • @Rubber_duck I'd recommend to step through your code line by line, to find the exact source of the error. Besides that follow Nathan's and UKMonkey's advice. – user0042 Jul 27 '17 at 15:49

1 Answers1

0

The problem was resolved using a for loop instead:

for(string line; getline(file,line);){

}

After reading those pages recommended by @NathanOliver, I am still not quite sure why eof is a bad idea. From what I gathered, is it because eof tries to read the next line irrespective of the fact that it might be the last line?

Astronomer
  • 109
  • 4