I'm getting a segmentation from fgets, but only sometimes. It's someone else's code, and I don't understand the makefile, so I'm debugging with printf statements... I put this at two parts of the main function: (I only create the variables *f and line once, but I fopen and fclose the file both times.)
FILE *f = NULL;
char line[1000];
if ((f=fopen(filename,"r+"))==NULL)
{
printf("Error opening file\n");
f=0;//...handle error... //(usually just call abort() or return -1
}
//f = rfopen(fname, "r+");
printf("f from eval_args: %d, filename %s\n",f,filename);
printf("trying to read from file...\n");
printf("%s\n",fgets(line, sizeof (line), f));
printf("...succeeded\n");
fclose(f);
which gives me two different outputs:
f from eval_args: 4609600, filename /correct/path/to/file
trying to read from file...
100
...succeeded
f prior to entering density profile: 4609600, filename /correct/path/to/file
trying to read from file...
Segmentation fault (core dumped)
I check that the file is correctly opened, and guard against reading more characters than will fit in 'line'. I saw in one forum that the filename shouldn't be more than 49 characters long... but a) that's a strange restriction and b) why does it work the first time?
Does anyone know what else I could check?
(null)
upon encountering a NULL string? – user529758fgets
as a separate statement, and then you should use the debugger to help you locate and examine the error. – Some programmer dude