Menu

False negative leak with asprintf

Pieter D
2023-11-14
2023-11-14
  • Pieter D

    Pieter D - 2023-11-14
    #include <stdio.h>
    int main()
    {
        char* test = NULL;
        test = malloc(5);
    
        return 0;
    }
    

    This gives with cppcheck --enable=all test.c --library=gnu.cfg
    test.c:9:5: error: Memory leak: test [memleak]
    return 0;
    ^
    test.c:6:10: style: Variable 'test' is assigned a value that is never used. [unreadVariable]
    test = malloc(5);
    ^

    But once I do:

    #include <stdio.h>
    int main()
    {
        char* test = NULL;
        test = malloc(5);
    
        (void) asprintf(&test, "%s_1", "test");
        return 0;
    }
    

    This gives no errors, while I was expecting 2 leaks here (the malloc and the asprintf allocation)

    If I do:

    #include <stdio.h>
    int main()
    {
        char* test = NULL;
        test = malloc(5);
    
        (void) asprintf(NULL, "%s_1", "test");
        return 0;
    }
    

    This gives following errors which are correct:
    test.c:9:5: error: Memory leak: test [memleak]
    return 0;
    ^
    test.c:8:21: error: Null pointer dereference [nullPointer]
    (void) asprintf(NULL, "%s_1", "test");
    ^
    test.c:6:10: style: Variable 'test' is assigned a value that is never used. [unreadVariable]
    test = malloc(5);
    ^

    Why is

     <memory>
        <alloc init="true" arg="1">asprintf</alloc>
        <dealloc>free</dealloc>
      </memory>
    

    from gnu.cfg not getting hit?

     

    Last edit: Pieter D 2023-11-14
  • CHR

    CHR - 2023-11-14

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/12186

     

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.