Home > front end >  crash for C map when deleting via iterator
crash for C map when deleting via iterator

Time:09-03

I have the following code which crashes

#include <map>
#include <iostream>

using namespace std;

int main()
{
        map<int,int> m;
        m[1]=2;
        m[2]=3;
        m[3]=4;
        m[4]=5;
        /*
        m.insert(std::make_pair(1,2));
        m.insert(std::make_pair(2,3));
        m.insert(std::make_pair(3,4));
        m.insert(std::make_pair(4,5));
        */
        for (auto it=m.begin();it!=m.end();)
        {
                cout << it->first << "->" << it->second << endl;
                if (it->first == 3) {
                        auto next =   it; // <------------------------
                        m.erase(it);
                        cout << "Restart " << endl;
                        it = m.begin();
                }
                else
                {
                          it;
                }
        }

        return 0;
}

The problem dissapears if I comment the line with <------------------ and I cannot explain myself why.

Any clues?

CodePudding user response:

Your map is this (showing the keys only)

{ 1, 2, 3, 4 }

You then loop through, find the 3, and erase the next element. Leaving this

{ 1, 2, 3 }

Now you start from the beginning again, find the same three again and delete the next element, but this time there is no next element. Therefore you get a crash,

CodePudding user response:

  1. what do you want to do by your code?
  2. the code run output is like below:
    1->2
    2->3
    3->4
    Restart 
    1->2
    2->3
    3->4
    crash....

it crash in second time loop becuase "3" is last element in the map. so "next" equals m.end(), when you erase it, it will crash.

  • Related