Getting fgets warning when trying to run optimized c file

186 Views Asked by At

This is part of a much larger file, but this is the only function in question. Here's the issue, if I compile it in gcc unoptimized, I will get everything I want without issues. However, if I try to compile it as gcc -c -pg -02 main.c, I get the following error message

1

There are 1 best solutions below

1
On BEST ANSWER

Like any other function that does input, fgets could fail for a variety of reasons. As you can find from its documentation, if this happens it will return NULL. However since you do not look at its return value, you would never know. That's what the compiler is trying to warn you about. If it fails, the array line will not contain valid input, and may contain garbage that would cause your program to misbehave if you try to process it.

(There are many situations where some warnings only happen with optimization on; this is because the compiler does a more detailed analysis of the code as part of the optimization process, which makes it more possible for it to detect such issues. But that's a good thing; it's not a problem with optimization or a reason not to use it.)

If fgets should fail, there's no obvious way for your program to recover, so the simplest approach is to just have it quit and display an error message. The perror function is a convenient way to do that; it prints a human-readable message corresponding to the error code from the errno variable which fgets should set.

So a rudimentary form of error checking here would be to replace your fgets line with:

if (fgets(line,MAX_LINE ,stdin) == NULL) {
    perror("Failed to read input");
    exit(1);
}

Some things you could improve later:

  • One possible reason for fgets to return NULL is end-of-file: if there was no input at all: the user hit the end-of-file key on their terminal (usually Ctrl-D on Unix, Ctrl-Z on Windows) or redirected input from an empty file. That's not exactly an error, and it won't result in an error code in errno, so perror may print a misleading message in this case. Try and fix this bug. You could distinguish the two cases using the ferror function.

  • If a line was successfully read but can't be parsed as a number, strtol will fail. You currently don't check for that either. Look up how it indicates this failure and handle it accordingly.