Why is the following code giving segmentation fault?
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
file = fopen("text","r");
if (file == NULL) printf("Error READING FILE");
if (ferror(file)) printf("error reading file"); //line 9
return 0;
}
Doing backtrace in gdb gives:-
> #0 0x00007ffff7ad9d30 in ferror () from /lib/libc.so.6 > #1 0x00000000004005fa in main () at test.c:9
If
fopenreturns NULL, then the file isn’t open; you’re passingNULLin toferror, which is invalid. You don’t have an open file to pass in; that’s whatNULLmeans, that it couldn’t give you a file pointer.ferroris for getting errors related to reading and writing the file, once it has actually been opened and you have the file to work with.If
fopenfails, and you want to get more information about why, you need to check theerrnoglobal variable, defined inerrno.h.This example shows how to fetch a string describing the error; you could also compare the value in
errnoagainst one of the possible values it could have, and do something different depending on what the error is. See thefopenman page, or the POSIX spec, for a list of possible errors to compare against. Here’s how you could check against various possible errors:(this is an expansion of something I originally wrote in a comment on another answer)