Reputation: 2269
for(std::list<MyClass *>::iterator it = m_currentJobs.begin(); it != m_currentJobs.end(); ++it)
{
request = *it;
if(request != NULL)
{
printf(request->status());
}
delete request;
m_currentJobs.erase(it);
}
Is it possible for the iterator to point to some garbage data beyond the end of the list?
Upvotes: 1
Views: 682
Reputation:
You make your iterator invalid by erasing it.
You may change your loop to:
std::list<MyClass *>::iterator it = m_currentJobs.begin();
while(it != m_currentJobs.end())
{
// ...
it = m_currentJobs.erase(it);
}
And to answer your question: Yes it is possible to have an invalid iterator (not limited to iterators past the end). Using these involves undefined behavior.
Upvotes: 6
Reputation: 247909
At the end of each iteration, you do this:
m_currentJobs.erase(it);
which invalidates it
.
Immediately afterwards, you do this:
++it
which is undefined behavior if it
is not a valid iterator.
Most likely, that is your problem.
std::list::erase
actually returns an iterator, pointing to the element after the deleted one. Reset it
to point to that, and your code should work a lot better. (Note that when this happens, you've already jumped to the next element, so you shouldn't also run ++it
in that iteration.)
Upvotes: 3