Menu ▾ ▴

False positive memleak when an allocation is returned through a conditional operator

Kaixuan Li
2026-11-17
2026-11-18
  • Kaixuan Li

    Kaixuan Li - 2026-11-17

    Hi,

    #include <stdlib.h>
    
    char *buf_new(size_t n)
    {
        char *p = malloc(n);
        return p == NULL ? NULL : p;
    }
    
    char *buf_new2(size_t n)
    {
        char *p = malloc(n);
        return p ? p : NULL;
    }
    
    $ cppcheck -q ternary.c
    ternary.c:6:5: error: Memory leak: p [memleak]
        return p == NULL ? NULL : p;
        ^
    ternary.c:12:5: error: Memory leak: p [memleak]
        return p ? p : NULL;
        ^
    

    In both functions p is returned to the caller on every path, so nothing leaks. The same check written as an if is not reported:

    #include <stdlib.h>
    
    char *buf_new(size_t n)
    {
        char *p = malloc(n);
        if (p == NULL)
            return NULL;
        return p;
    }
    
    $ cppcheck -q ternary_if.c
    

    In CheckLeakAutoVarImpl::ret() the returned variable is only recognized when the token before it is one of return ( { , * (lib/checkleakautovar.cpp:1208) and the token after it is one of ) } ; , + (lib/checkleakautovar.cpp:1225). Neither list contains ? or :, so ? p : and : p ; are not seen as returning p. The conditional operator in an assignment (x = p ? p : nullptr;) was fixed in #8235 (test assign26), but the return statement still has the old token lists. Accepting ? and : in those two lists, or walking the AST of the return expression, should fix it.

    Reproduced with 2.20.1 and current main (530e59f).

     
  • CHR

    CHR - 2026-11-18

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

     

Log in to post a comment.