The code is as follows. It compiles successfully(no error message when i compile it with g++), has correct out put and produce a graph. But the graph appeared for 2 seconds and disappeared (The file of the graph is still produced and saved in the directory) and i got a segmentation fault at the end of all the outputs. I know a segmentation fault is caused by writing in the wrong part of the memory. It basically does all the things that I want but I have no idea where is the fault comes from. Can anyone tell me what is going on? Thanks!
-----------------------------------------------------------------------
int main ()
{
//input the data.txt file into the program.
ifstream fin("data.txt");
//The number of data points (N) is determined.
int N=0;
while (fin.ignore(100,'\n'))
N++;
fin.clear();
fin.seekg(0);
//The memory is reserved to store the data.
double* xdata=new double[N];
double* ydata=new double[N];
//Reading the data into the arrays.
for(int i=0;i<N;i++)
fin >> xdata[i] >> ydata[i];
fin.close();
//seven sums are defined and are initialsed by a for-loop.
double x_sum=0;
double x2=0;
double x3=0;
double x4=0;
double y_sum=0;
double y1=0;
double y2=0;
//M is a 3x3 array and is defined as the following.
double M[3][3]={{x3*x3-x2*x4,x_sum*x4-x2*x3, x2*x2-x_sum*x3},
{x_sum*x4-x2*x3,x2*x2-N*x4,N*x3-x_sum*x2},
{x2*x2-x_sum*x3, N*x3-x_sum*x2,x_sum*x_sum-N*x2}};
//v is a 1D array with 3 elements and is defined as the following.
double v[3]={y_sum,y1,y2};
//p is a 1D array with 3 elements storing the coefficients of the fit
//and is defined using a for-loop.
double p[3]={0.0};
for(int i=0;i<=2;i++)
{
for(int j=0;j<=2;j++)
p[i]+=M[i][j]*v[j]/(x4*x_sum*x_sum+N*x3*x3+x2*(x2*x2-N*x4-2*x_sum*x3));
cout << p[i] << "\n";
}
DislinInit(N, "", "Quadratic Fit");//A graph is produced.
//fit is an array of size N storing the fit function values.
double* fit=new double[N];
for(int i=0; i<=N;i++)
fit[i]=(p[2]*xdata[i]+p[1])*xdata[i]+p[0];