Segmentation fault (core dumped)

I am trying to read values from a txt file into an array in order to find their mean, median, and stanDev. Stuck in with getting the values from txt file into array. Error "Segmentation fault (core dumped)" keeps popping up. Heres my code

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<cmath>

using namespace std;

double mean_array(int [], int);
double stanDev(double [], double, double);

int main()
{
ifstream inFile;

string filename;

cout << "Which file would you like to open? Include the file's name and extension: "
<< endl;
cin >> filename;

inFile.open(filename.c_str()); //attempt to open file for input

if(!inFile.fail())
{
cout << "A file by the name " << filename << " exists."
<< endl;
}

int value;
int array[1174]; int i = 0;

inFile >> value; //stores the first number in variable value

while (inFile.good()) //continue until the end of the file
{
array[i] = value;
i++;
cout << value << " ";
inFile >> value; //stores next number in variable value
}

inFile.close(); //closes the file

return 0;
}
Last edited on
If you ran this under a debugger, it would tell you exactly which line is the problem. If you're going to be programming in the future, the time spent learning to use the debugger will save you literally thousands of hours.

Anyway, a segFault occurs when you try to read or write memory that the OS thinks doesn't belong to you. Since you're writing to an array, and you're not taking any precautions to ensure that you're not writing beyond the end of the array, I'd guess that you're writing beyond the end of the array.

You can double check by putting
cout << "Writing to array element " << i << endl;
in the array writing loop. If it writes to element 1174 or later, you're writing off the end of the array and into memory that you shouldn't be.

Topic archived. No new replies allowed.