[Solved] Segmentation fault from sscanf in a loop in C


Using feof() is a bad idea as it can return zero, and then the next line of input can encounter end of the file – which can give unexpected errors

Also fgets() returns NULL if an error occurs, including encountering end of file.

Imagine your loop has been going along happily, and has just read the second last line in the file. On the next iteration, feof() will return zero, so the first statement strings = fgets(strings, __MAXLEN__, prova) will succeed. The second one – inside the do-while loop – will set strings to NULL, so will pass the NULL to your readCompl() function – which will, in turn, try to read from the NULL using sscanf(). sscanf() gives undefined behaviour if given a NULL – (one symptom of which can be a segmentation violation – the program accessing memory it shouldn’t).

The solution needs to be in two parts. Firstly, don’t use feof() to control any loop. Second, check the result of functions you call (fgets(), sscanf(), etc) and – if you need to – use their return value to control loops.

1

solved Segmentation fault from sscanf in a loop in C