Menu

Clarification Needed and possible false positive

2020-04-02
2020-04-02
  • Frédéric Pröls

    CppCheck 1.89 and 1.90 report

    (error) Using iterator to local container 'test' that may be invalid. [invalidContainer]

    On this code

      std::vector<int> test{ 1,2,3,4,5,6 };
    
      auto it = test.begin()+2;
      test.erase(it+1); // works
      //test.erase(it); // assertion in STL msvc-14.1
    
      std::cout  << *it;
    

    Some interpret the message as in cppcheck is unsure if this is an error or not. I interpret this as cppcheck is sure that it is an error to access an iterator that is not guaranteed to be valid anymore.

    Further I find the category [invalidCOntainer] a bit misleading as it should be the iterator that got invalidated not the container. The error text is also not helping.

    About the false positive:
    Iterators at or beyond the erased element are invalidated, not the ones before. Therefore, the code should be OK and the commented-out line would be incorrect.

     
  • Paul Fultz

    Paul Fultz - 2020-04-02

    Some interpret the message as in cppcheck is unsure if this is an error or not.

    It says 'maybe' because it becomes invalid only if there is a resize. So calling reserve before hand would make things like push_back stable while the number of elements added are less than the reserved size.

    Further I find the category [invalidCOntainer] a bit misleading as it should be the iterator that got invalidated not the container. The error text is also not helping.

    That is a good point. It should probably be renamed to invalidContainerLifetime or invalidContainerReference. This actually checks both references and iterators.

    Iterators at or beyond the erased element are invalidated, not the ones before. Therefore, the code should be OK and the commented-out line would be incorrect.

    This is similiar to the FP of using reserve+push_back which we should probably do better at detecting in cppcheck.

     

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.