Menu

False negative: file resource leaks missed in loop with early returns

Rodri
2026-08-02
2026-08-03
  • Rodri

    Rodri - 2026-08-02

    Hi, I found a false negative regarding the rule resourceLeak.

    Cppcheck reports resourceLeak for the first program, but it misses the second program, which leaks file resources through a loop and early-return paths.

    First program

    #include <stdio.h>
    
    int main()
    {
        const FILE *a = fopen("good.c", "r");
        if (!a)
            return 0;
    
        return 0;
    }
    

    Cppcheck reports:

    <error id="resourceLeak" severity="error" msg="Resource leak: a" ...>
    

    Second program

    #include <stdio.h>
    
    int main() {
      const FILE *a = fopen("good.c", "r");
      if (!a)
        return 0;
      for (int i = 0; i < 5; i++) {
        FILE *b = fopen("temp.c", "r");
        if (!b)
          return 0;
        char c = fgetc(b);
        if (c == 'X') {
          return 0;
        }
        fclose(b);
      }
      return 0;
    }
    

    In this program, a is never closed after a successful fopen. In addition, when c == 'X', the function returns before fclose(b), so b is also leaked on that path.

    Actual result

    Cppcheck reports no resourceLeak warning for the second program.

    Expected result

    Cppcheck should report resourceLeak for a, and it should also report a leak for b on the c == 'X' early-return path.

    Verification

    The issue was reproduced with:

    cppcheck --output-format=xmlv2 --enable=all resource_leak_loop_early_return.cpp
    

    Version: 2.21.0

     
  • CHR

    CHR - 2026-08-03

    Looks like an instance of https://trac.cppcheck.net/ticket/2565

     

Log in to post a comment.