Menu

Memory leak not reported in code that includes loops

Øyvind P
2022-02-24
2026-07-17
  • Øyvind P

    Øyvind P - 2022-02-24

    Using the snippet below cppcheck reports 'memleak' in addition to 'unreadVariable' and 'unusedAllocatedMemory':

    int main()
    {
        char * buf = malloc(10);
    
        return 0;
    }
    

    cppcheck testmemleak.c --enable=all --inconclusive

    But 'memleak' is no longer reported when the code includes a for loop:

    int main()
    {
        for (int n=0; n < 1; n++) { }
    
        char * buf = malloc(10);
    
        return 0;
    }
    

    'unreadVariable' and 'unusedAllocatedMemory' are still reported however.

    Is this a bug or am I missing something obvious?

    Same behavior using a dummy while loop. Tested cppcheck versions 2.6, 1.9 and HEAD.

     
  • Øyvind P

    Øyvind P - 2022-02-25

    Inspired by this post in a recent discussion also involving leaks and loops I tested if a leak is detected when the pointer returned from malloc is stored in a member of a struct.

    Indeed, in the following code cppcheck detects a memory leak:

    int main()
    {
        for (int n=0; n < 1; n++) { };
    
        struct { char * buf; } test;
    
        test.buf = malloc(10);
    
        return 0;
    }
    
     
  • CHR

    CHR - 2022-02-26

    The first case should be handled by checkScope(), which however bails out when it encounters a loop. The second leak is found by checkStructVariable().

     
    • correctmost

      correctmost - 2026-07-16

      Is there a bug report for the FN memleak case mentioned above?

      int main()
      {
          for (int n=0; n < 1; n++) { }
      
          char * buf = malloc(10);
      
          return 0;
      }
      

      I still see the issue with main (d32c01d) and wasn't sure if it is expected behavior / works as designed. Thanks!

       
      • CHR

        CHR - 2026-07-17

        See https://trac.cppcheck.net/ticket/11786 and tickets mentioned therein.

         

Log in to post a comment.

Monday.com Logo