No change. So I moved it to my webpage from Windows and back down to Linux. Now it appears that I have forgotten bsic C, and my hardback edition of Kernighan and Ritchie is gone. (Found it!)
Why does this segmentation fault on fgets?
#include
#include
int main (int argc, char *argv[])
{
FILE* inputFile;
char* inputString;
inputString = malloc(500);
inputFile = fopen(argv[1], "r");
inputString = fgets(inputString, 500, inputFile);
printf("%s\n", inputString);
exit(0);
}
I started with char inputLine[500] with same result. Faults only in the debugger. gdb works fine; DDD which uses gdb to provide a GUI fails. I wish ancient releases of debian (the base for linuxcnc) supported modern Eclipse.
Using gdb from the command line takes me back to the 1980s, and reminds me why I helped develop a GUI high-levcl language debugger back then for Kontron Electronics. I am relearning C, with the inevitable pointer reference problems that led to C++.
You are re-assigning inputString with the result of fgets (which is an int).
ReplyDeleteAlso, when running from the debugger, did you remember to do a set args filename.txt? The fopen will fail if argv[1] isn't set.
A quick search suggests that the file isn't in the current directory and fopen is returning NULL.
ReplyDeleteI would check inputFile != null to confirm the file open worked, and not assign inputString = fgets(...); rather just test the return value != null to confirm the fgets successfully copied;
ReplyDeleteif (argc < 2) {
/* print usage string */
exit(-1);
}
inputFile = fopen (argv[1] , "r");
if (inputFile == NULL) perror ("Error opening file");
else {
if ( fgets (inputString, 500 , inputFile) != NULL )
printf("%s\n", inputString);
else
printf("Could not read from file\n");
fclose (pFile);
}
The only thing I see that could cause a seg fault on the fgets line is if the file open failed for some reason.
Thanks for all the help. I am slowly working my way through the real code. char *list[] means to malloc the memory before copying a string into it. The things you forget.
ReplyDelete