Reputation: 697
While i was developing a C++ application,
I was using a simple list<int> *somelist = new list<int>();
that contains data.
I was trying to iterate this list using something like this:
for (list<int>::iterator j=somelist->begin();j!=somelist->end();j++)
{
//do something with *j
}
When i was doing something with the pointer j
because of a chain reaction the data that i was going to access was removed from the list and no longer exists.
So, i am being prompted with an Access Violation Error Msg.
Can someone tell me how to identify if the pointer j
is a bad ptr
Upvotes: 1
Views: 1150
Reputation: 3119
With multi-threading your iterator can become invalidated if some other thread removes elements from the list. With a low-level programming such as C++, there is no way to detect this problem once it has happened. Your best bet is to "prevent this from happening."
Use synchronization functions (e.g., WaitForSingleObject
in Windows) to control access to shared STL containers.
Upvotes: 0
Reputation: 507413
The bug in your code is that you need to handle this when you still know you removed it. Afterwards you cannot handle it anymore. In the following example, dosomething
returns true when the element should be removed
for (list<int>::iterator j=somelist->begin();j!=somelist->end();) {
if(dosomething(j)) {
/* should remove it! */
j = somelist->erase(j);
} else {
++j;
}
}
Upvotes: 1