std::vector<int> va; // and push_back 1~100
std::vector<int>::iterator i = va.begin();
for(i; i != va.end(); )
{
if((*i) == 5) va.erase(i);
else i++
}
This code is 100% crashed when debug runtime.
But don`t crash this code when release runtime.
Why this happen?
What is different debug and release mode in this code?
As others have pointed out, the crash is due to the invalidated iterator that you are continuing to use after calling
va.erase().Now, as to why it works in Release mode, is that in some cases the iterator for a
std::vector<>in Release mode is a simple pointer into a dynamically allocated array. When you call erase, the iterator continues to point at the same element of the array while the contents of the array have been moved by theerasefunction. This is undefined behavior and Standard Library implementation specific, but very common. Under no circumstance should you rely on the behavior in portable code.However, on some Standard Library implementations, Debug mode iterators perform checking and are more complicated than simple pointers. As such, they can detect that you are doing something that isn’t legal and intentionally cause a crash, so that you can recognize your error.