Menu

False positive: [invalidContainer]: vector of pointers, back, pop_back

2020-07-05
2020-07-06
  • Andreas Grob

    Andreas Grob - 2020-07-05
    #include <vector>
    #include <iostream>
    
    struct A {
        ~A() { std::cout << "deleted\n"; }
    };
    
    int main() {
        std::vector<A *> v;
        A *a = new A();
        v.push_back(a);
        A *b = v.back();
        v.pop_back();
        std::cout << "pop_back\n";
        delete b;
    }
    

    output:

    $ ./a.out
    pop_back
    deleted
    

    cppcheck: commit 5cb3aac
    built with: make MATCHCOMPILER=yes FILESDIR=/usr/share/cppcheck HAVE_RULES=yes

    $ cppcheck main.cpp
    Checking main.cpp ...
    main.cpp:15:12: error: Using pointer to local variable 'v' that may be invalid. [invalidContainer]
        delete b;
               ^
    main.cpp:12:12: note: Pointer to container is created here.
        A *b = v.back();
               ^
    main.cpp:13:5: note: After calling 'pop_back', iterators or references to the container's data may be invalid .
        v.pop_back();
        ^
    main.cpp:9:22: note: Variable created here.
        std::vector<A *> v;
                         ^
    main.cpp:15:12: note: Using pointer to local variable 'v' that may be invalid.
        delete b;
               ^
    
     
  • Daniel Marjamäki

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

     

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.