cwarningsfgetsstrtol

Getting fgets warning when trying to run optimized c file


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


Solution

  • 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: