Menu

Warning that is possibly wrong?

2025-02-05
2025-02-07
  • Maury Markowitz

    Maury Markowitz - 2025-02-05

    First post here, please be gentle!

    I have some C code performing a BASIC INPUT statement while reading from a file. The opening bit of this code is...

        char buffer[MAX_INPUT_LENGTH];
        int type;
    
        // get the stream
        int channel = floor(evaluate_expression(statement->parms.generic.generic_parameter).number);
        FILE* fp = handle_for_channel(channel);
        if (fp == NULL) {
          handle_error(ern_FILE_NOT_OPEN, "Attempt to INPUT from a file that has not been OPENed");
          // and make sure we can read it
          if (!channel_is_readable(channel)) {
            handle_error(ern_FILE_NOT_INPUT, "Attempt to INPUT from a file that is read-only");
          }
        }
    
        // read one line from the file, if it's empty, warn and return
        if (fgets(buffer, sizeof buffer, fp) == NULL) {
          handle_error(ern_OUT_OF_DATA, "Reached the end-of-file while performing INPUT");
          return;
        }
        long len = strlen(buffer);
    

    The question has to do with the fgets line, which in cppcheck is returning:

    Either the condition 'fp==NULL' is redundant or there is possible null pointer dereference: fp
    

    But, to my not very expert eye, I am not comparing fp to null. Am I misinterpreting what is going on here, or is this a spurious warning?

    Complete code here, it is small and should easily make on practically anything:

    https://github.com/maurymarkowitz/RetroBASIC

     
  • CHR

    CHR - 2025-02-05

    Does handle_error() return or abort? If it returns, fp can be used even if it is NULL.

     
  • Maury Markowitz

    Maury Markowitz - 2025-02-07

    handle_error MAY abort, but will not if a TRAP is set, which it often is during I/O.

    But the warning is not related to that I don't think?

     
  • Maury Markowitz

    Maury Markowitz - 2025-02-07

    Ohhh, wait now I see what you mean. It's not complaining about fp==NULL on this line, it's saying the one above is the issue. Now I get it!

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.