Menu

False positive in Cppcheck 2.10: invalidContainer

2023-02-24
2023-02-25
  • Rustam Miftakhutdinov

    Cppcheck 2.10 reports a false positive when run on a C++ file with the following code. Please see comments in the code for details.

    #include <vector>
    #include <cstdio>
    
    template<typename T>
    int g() { return 0; }
    
    int f(int t) {
      std::vector<int> v(1);
      // the auto type deduction on the following line seems to be the cause of
      // the false positive, because if either
      //  - the type of itr is specified explicitly as std::vector<int>::iterator, or
      //  - g<int>() is replaced with an equivalent non-templated function,
      // then the false positive issue is no longer reported by Cppcheck.
      auto itr = v.begin() + g<int>();
      std::vector<int> v2(itr, v.end());
      v.erase(itr, v.end());
      // False positive issue with message
      // "error: Using iterator to local container 'v' that may be invalid. [invalidContainer]"
      // reported on the next line
      v.push_back(v2.size());
      return v[0];
    };
    
    int main (int argc, char *argv[]) {
      printf("Answer: %d\n", f(0));
      return 0;
    }
    
     
  • CHR

    CHR - 2023-02-25

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

     

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.