Home > OS >  Why erasing element from map while looping it is not causing crash everytime it happens?
Why erasing element from map while looping it is not causing crash everytime it happens?

Time:12-08

So, here is my function

void Timers::RemoveTimer(DWORD id)
{
    auto it = m_mapTimers.begin();
    for ( ; it != m_mapTimers.end();   it) {
        if (it->first.second == id) {
            m_mapTimers.erase(it);
        }
    }
}

And it clearly should not remove element this way, but what is interesting to me, is why the crash is not constant? Program can call this function few thousand times untill it goes down.

Also, kind of side question, why there was no crashes on c 98? I get them after porting to c 20, without any change to class.

CodePudding user response:

To safely remove elements from a container you should write it like this:

void Timers::RemoveTimer(DWORD id)
{
    auto it = m_mapTimers.begin();
    for ( ; it != m_mapTimers.end(); ) {
        if (it->first.second == id) {
            it = m_mapTimers.erase(it);
            continue;
        }
        it  ;
    }
}

As for your question, this code may crash if it violates a memory segment that does not belong to it by trying to access it. It depends where the memory you are accessing is located in the address space, which is different every time the program runs.

CodePudding user response:

More C Idioms/Erase-Remove: To eliminate elements from a STL container to reduce the size of it.

void Timers::RemoveTimer(DWORD id) {
  m_mapTimers.erase(std::remove(m_mapTimers.begin(), m_mapTimers.end(), id),
                    m_mapTimers.end());

}
  • Related