Menu

Potential false positive - "Iterator 'it' used after element has been erased"

Erik
2018-08-19
2021-01-26
  • Erik

    Erik - 2018-08-19

    I'm using cppcheck built from source.

    The following code gives error: [test.cpp:15] -> [test.cpp:17]: (error) Iterator 'it' used after element has been erased.

    namespace cereal
    {
      class InputArchive
      {
        private:
          template <class T, traits::EnableIf<traits::has_member_serialize<T, ArchiveType>::value> = traits::sfinae> inline
      };
    }
    
    void Do_Work()
    {
        std::vector<std::string> m_background_task_queue;
    
        std::vector<std::string>::iterator it = m_background_task_queue.begin();
        while (it != m_background_task_queue.end())
        {
            it = m_background_task_queue.erase(it);
        }
    }
    

    The following does NOT give any error message (iterator type changed to auto):

    namespace cereal
    {
      class InputArchive
      {
        private:
          template <class T, traits::EnableIf<traits::has_member_serialize<T, ArchiveType>::value> = traits::sfinae> inline
      };
    }
    
    void Do_Work()
    {
        std::vector<std::string> m_background_task_queue;
    
        auto it = m_background_task_queue.begin();
        while (it != m_background_task_queue.end())
        {
            it = m_background_task_queue.erase(it);
        }
    }
    

    The following also does not give any error message:

    void Do_Work()
    {
        std::vector<std::string> m_background_task_queue;
    
        std::vector<std::string>::iterator it = m_background_task_queue.begin();
        while (it != m_background_task_queue.end())
        {
            it = m_background_task_queue.erase(it) ;
        }
    }
    

    This gives an error message:

    void Do_Work()
    {
        std::vector<std::string> m_background_task_queue;
    
        std::vector<std::string>::iterator it = m_background_task_queue.begin();
        while (it != m_background_task_queue.end())
        {
            it = m_background_task_queue.erase(it) - 1;
        }
    }
    
     

    Last edit: Erik 2018-08-30
  • CHR

    CHR - 2021-01-26

    Neither of the two cases reproduces with 2.3.

     

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.