Menu

Different ways of checking the return value of alloc functions affects the results

Amarghosh
2024-08-08
2024-08-09
  • Amarghosh

    Amarghosh - 2024-08-08

    In the following snippet, cppcheck does not report a memleak if the return value is explicitly compared against a value, as in the case of a2. But at the same time, if we just check if (getaddrinfo()) as in the case of a1, which is a widely used pattern to check if the function returned zero or not, it reports a false positive memleak. Invocation command was cppcheck --library=posix.cfg main.c, and the version was 2.14.2

        struct addrinfo *a1 = NULL;
        if (getaddrinfo("a", "b", NULL, &a1)) {
            return -1; // false positive memleak reported here
        }
        freeaddrinfo(a1);
    
        struct addrinfo *a2 = NULL;
        if (getaddrinfo("a", "b", NULL, &a2) != 0) {
            return -1; // no false positive memleak here
        }
        freeaddrinfo(a2);
    

    It would be nice if you could treat if (func()) same as if (func() != 0).

     
  • CHR

    CHR - 2024-08-08

    Thanks for reporting, fixed by https://github.com/danmar/cppcheck/pull/6671

     
  • Amarghosh

    Amarghosh - 2024-08-09

    Thank you! That was really fast :)

     

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.