Menu

False positive: incorrect memleak with lambda functions

2020-06-30
2020-06-30
  • Stefan Löffler

    Stefan Löffler - 2020-06-30
    struct S { int * p{nullptr}; };
    
    int main()
    {
        S s;
        s.p = new int[10];
        for (int i = 0; i < 10; ++i) {
            s.p[i] = []() { return 1; }();
        }
        delete[] s.p;
        return 0;
    }
    

    produces

    false-memleak.cpp:8:19: error: Memory leak: s.p [memleak]
      s.p[i] = []() { return 1; }();
                      ^
    

    Interestingly, using a int * directly (rather than s.p) does not produce the false positive. Replacing the lambda function invocation by a literal or a "normal" function invocation does not trigger the false positive either.

     
  • Daniel Marjamäki

    Thanks! I created ticket https://trac.cppcheck.net/ticket/9793

     

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.