0

Below is my code. I erase the element of which value is 3 and obtain next iterator by erase() function. But when I tried to print its value.It crashed to my surprise. Anyone know the problem??

int main()
{
    std::vector<int> a = {1, 2, 3, 4, 5}; 
    for(vector<int> ::iterator it=a.begin();it!=a.end();it++)
    {
        vector<int> ::iterator g;
        if(*it==3 )
        {
            g=a.erase(it);
        }
        cout<<*g<<endl;
    }
Caiyi Zhou
  • 143
  • 1
  • 9
  • The setup for managing `it` is wrong. And the use of `g` in this is rather pointless, and the dereference dump of `*g` in all cases where `*it == 3` is *false* immediately invokes undefined behavior. the increment step of the `for` loop should be empty, the statement within the `if` condition should be `it = a.erase(it);`, and an `else { ++it; }` should follow the `if` block. That, assuming I understand what you're trying to do here. There are dozens of duplicates of this encounter on this site. I'll try and find one to close this out. – WhozCraig Mar 12 '21 at 07:43

1 Answers1

3

Why my program crash after dereference of returned iterator of erase() function?

After you have indirected through that iterator and inserted it into cout, you proceed to increment it which is (potentially) invalid, and then also compare it to another iterator and later indirect through it. This results in undefined behaviour.

Even before that, in case *it != 3, you indirect through g which is uninitialised, which results in undefined behaviour.

eerorika
  • 232,697
  • 12
  • 197
  • 326