Reputation: 53
I have the problem that some parts of my code run in the Release mode without a problem, but errors appear in the Debug mode.
Setup: c++ 17 - Visual Studio 2019
To show the difference I wrote a little testcode:
int main()
{
//Vector containing 20 lists with length of 10 each. Every Element = 10
std::vector<std::list<int>> test(20, std::list<int>(10,10));
std::cout << test[6].front() << std::endl; //test if initialization worked
std::list<int>::iterator test_iter;
for (test_iter = test[6].begin(); test_iter != test[6].end(); test_iter++)
{
std::cout << *test_iter << std::endl;
test[6].erase(test_iter);
}
}
In Release it works fine
But in Debug I get this
Does anyone have an idea why there is a difference between the both mode and how I can adjust it, so the Debug mode works fine as well?
Thanks for your help in advance!
Best regards David
Upvotes: 4
Views: 4384
Reputation: 66459
The problem is not so much that it doesn't work in debug, as it is that it appears to work in release - the code is equally broken in both, but the debug version of the library has some extra error-checking code.
The error message is a bit cryptic, but what it's trying to say is that you're attempting to increment an iterator that can't be incremented.
This happens because test[6].erase(test_iter);
invalidates test_iter
, and using it after that is undefined.
erase
returns an iterator to the element following the erased element, and you can use this iterator instead of incrementing:
for (test_iter = test[6].begin(); test_iter != test[6].end(); /* empty */)
{
std::cout << *test_iter << std::endl;
test_iter = test[6].erase(test_iter);
}
Upvotes: 9