Hey im getting a segmentation fault when running my program.
I've narrowed it down to fgets in one of my functions.
Im newish to programming and i also used gbd to find the segfault.
The program does some of data manipulation, the function where the problem is reads two coloumns of data(doubles) from a file(180000 lines) into an array. the array is then used to do stuff, then populated with data from another similar file and so on....
This is done about 1200 times, but always segfaults and iteration 1018.
I had an earlier problem where it segfaulted at 500ish and was due to not fclose()'ing the file. But now the same problem but i cant seem to work out why its happening again!
Im using a gcc complier. Below is the gdb results and code of function.
Thanks alot for any help.
Cheers.
Code:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff78194dd in fgets () from /lib/libc.so.6
(gdb) backtrace
#0 0x00007ffff78194dd in fgets () from /lib/libc.so.6
#1 0x0000000000415dff in populatedata ()
#2 0x000000000041592e in integration ()
#3 0x0000000000415839 in main ()
The function code.
Code:
/** *ptr is pointer to beginning on outside declared array & *fn is pointer to the string with the file name where data is to be read **/
int populatedata(double *ptr,char *fn)
{
double column1, column2;//Temp variables for readingline from data file
char line[49]; //width of line parameter for fgets
int i=0;
FILE *fi;
fi = fopen(fn, "r");//Open data file
int before = 2; //for skipping the first 2 lines of data file
int skip = 0;
while (fgets(line,49,fi)!=NULL) //get each line from data file till EOF
{
if (skip < before)//skip first 2 lines
{
skip++;
} else {
//read the 2 data values on line from file into column vaiables.
sscanf(line, "%lf %lf", &column1, &column2);
*ptr=column2;
ptr++;
i++; //increment down the file
}
}
fclose(fi);
return 0;
}