Search code examples
c++loopsfile-iofault

My program is giving me a segmentation fault (c++)


My program reads a text file line by line to get information about a group of people who have made donations. It uses an array of structures to store the information (name, donation amount). The first line of the text file is the number of contributors. From then on the lines represent the name and value of a donation. eg:

3
Kyle Butler
10340
James Wright
5006
John Smith
10000

Then, if their donation is 10,000 or more, their name and donation value is outputted to the screen under the heading "grand patrons" otherwise, it appears under the heading "patrons"

The problem is, when i run the program, it gives me a segmentation fault with no evidence of the program outputting anything to the screen. Can someone please tell me what is going on here? I'm fairly new to the language.

#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <cctype>
#include <cstdlib>

using namespace std;

struct contribute {
    char Name[100];
    int contribution;
};

int main()
{

    char tempstore[100];
    int linecount=1;
    int pointerindex=0;
    ifstream inputfile("myfile.txt");

     if (!inputfile.is_open()){
         cout << "Error opening file";
     }

    inputfile.getline(tempstore, 20);
    int contributors = atoi(tempstore);
    contribute carray[contributors]; 

    while (!inputfile.eof()){
        if(linecount ==1){
            linecount++;
            continue;
        }

        inputfile.getline(tempstore, 20);


         if ((linecount % 2) == 0){
            strcpy( (carray[pointerindex]).Name, tempstore);

         }
         else {
             (carray[pointerindex]).contribution = atoi(tempstore);
         }


         ++linecount;
         ++pointerindex;
    }




    cout << "\n#####--#-Grand Patrons-#--#####\n";

    for (int i=0; i<contributors; i++){
        if (carray[i].contribution >= 10000){
            cout << "Name:  " << carray[i].Name << endl;
            cout << "Contribution:  " << carray[i].contribution << endl << endl;
        }
    }

    cout << "\n#####--#-Patrons-#--#####\n";

    for (int d=0; d<contributors; d++){
        if (carray[d].contribution < 10000){
            cout << "Name:  " << carray[d].Name << endl;
            cout << "Contribution:  " << carray[d].contribution << endl << endl;
        }
    }  

    inputfile.close();

    return 0;
}

Solution

  • You're incrementing pointerindex on every pass through the loop, rather than just after you read in the contribution amounts. So by the time you get to reading in 5006, you have pointerindex == 3, which causes a segfault on carray[pointerindex].

    Move ++pointerindex into the else statement.