Menu

Memory leak not reported in code that includes loops

Øyvind P
2022-02-24
2022-02-26
  • Ø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().

     

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.