Erasing vector element crashing the program - c++

Why the follwoing code is failing ?
typedef vector<SOCKET /*socket*/> UIConnection;
UIConnection::iterator itrUICon;
for ( itrUICon = m_ListUIConnection.begin();itrUICon != m_ListUIConnection.end();itrUICon++)
{
if (*itrUICon == nSock)
{
itrUICon = m_ListUIConnection.erase(itrUICon);
}
}

You must remove the ++itrUICon in the for instruction.
UIConnection::iterator itrUICon;
for ( itrUICon = m_ListUIConnection.begin();itrUICon != m_ListUIConnection.end(); )
{
if (*itrUICon == nSock)
{
itrUICon = m_ListUIConnection.erase(itrUICon);
}
else ++itrUICon;
}

Probably because you are erasing the last item in the vector and then incrementing itrUICon in the increment part of the for statement when it is already equal to .end().
Prefer using the erase()/std::remove() idiom or at least move the increment out of the for statement and only perform it if you didn't preform an erase.

Related

Map/iterator incremental error

The following code throwing debug assertion map/iterator incremental error ..
void ClassA::Remove()
{
std::map<int, CVClassB*>::iterator it(m_p.begin());
while ( it != m_p.end() )
{
if (it->first >= 0)
{
m_p.erase(it);
it++;
}
}
}
Can you please let me know what is the error
std::map::erase invalidates the iterator on which it operates. So it is not safe to increment it afterwards. But erase() does return the next iterator for you:
it = m_p.erase(it);
Also, you only increment it inside the if, so unless all the keys are >=0, you will get stuck in an infinite loop. You probably wanted something like:
// delete all keys >= 0
if (it->first>=0) {
it = m_p.erase(it); // erase and increment
}
else {
++it; // just increment
}
Also, as Vlad's answer alludes to, who manages the lifetime of the CVClassB*? Do you need to delete it? Why use a pointer at all, you can probably store the value in the map directly. (Or use a smart pointer).
Write the loop like
while ( it != m_p.end() )
{
if (it->first >= 0)
{
it = m_p.erase(it);
}
else
{
++it;
}
}
Also it seems you should delete the object pointed to by the erased iterator.
For example
delete *it;
it = m_p.erase(it);
Your invalidating the iterator by removing inside the loop but in any case all that does is clear the map. Just call m_p.clear() and it will do exactly what you are trying to do. Although not sure what your trying to do is what you intended to do but that's another issue.
If you want to delete the objects pointed to then delete them then clear the map.
for(item : m_p)
delete item->second;
m_p.clear();
//done

c++ boost map program crash after erase

I have a problem and dont know how to proper solve it or WHY the error appear.
To my problem:
I have 1 loop which execute a function every 2 seconds. That functions does a for() function and erase all entrys which remaining time is at 0. If remaining time is not 0 then it will decrease it by 2000 (2sec).
But after erasing an entry the program crashes...
boost map:
boost::unordered_map<unsigned int, sBUFF_INFO*> p_BuffInfo;
function which get executed from 2 seconds loop
void CSkill::DecreaseAllBuffRemTime()
{
for( itertype(p_BuffInfo) it = p_BuffInfo.begin(); it != p_BuffInfo.end(); it++ )
{
sBUFF_INFO* buff = it->second;
if(buff != NULL)
{
if(buff->dwTimeRemaining <= 0)
{
this->DelPcBuffInfo(buff->tblidx)
}else{
buff->dwTimeRemaining -= 2000;
}
}
}
}
DelPcBuffInfo function:
void CSkill::DelPcBuffInfo(unsigned int tblidx)
{
p_BuffInfo.erase(tblidx);
}
Now after DelPcBuffInfo gets executed the program crash.
At this line it crash:
sBUFF_INFO* buff = it->second;
At debug:
Unhandled exception at 0x00578e0f in GameServer.exe: 0xC0000005:
Access violation reading location 0xddddddd9.
it + node_ = hash_ CXX0030; Error: expression cannot be evaluated
I dont really understand why this error appear..
edit:
If I add a "return" after this->DelPcBuffInfo(buff->tblidx) then the program dont crash..
Adding or removing items from a container will often invalidate your iterators. Check the documentation for unordered_map iterators or here: Iterator invalidation in boost::unordered_map
the correct idiom is
for( itertype(p_BuffInfo) it = p_BuffInfo.begin(); it != p_BuffInfo.end(); )
{
sBUFF_INFO* buff = it->second;
if(buff != NULL)
{
if(buff->dwTimeRemaining <= 0)
{
it = this->DelPcBuffInfo(buff->tblidx)
}else{
buff->dwTimeRemaining -= 2000;
it++;
}
}
}
ie dont increment in the loop. Instead increment if you dont delete otherwise have the delete operation return the new iterator. Thats why remove returns an iterator pointing at the next element
This is courtesy of the awesome Scott Myers
To add to the existing answers pointing out the erase-iterator idiom: The reason for you crash is that the iterator it is invalidated due to the removal of the element. Thus, the increment on the (invalid) operator causes undefined behaviour and it will point to some arbitrary memory block. Dereferencing the "iterator" then crashes your program.
To avoid this problem, apply the idiom as demonstrated in the other answers, that is
* Use the iterator version of erase. It returns an iterator to the next element ( which may be end())
* Use the return value of this erase as new value of it. Since it already points to the next element, do not increment again (otherwise you may skip an element in your map or cause undefined behaviour if it already points to the end of the map.
* Only increment the iterator yourself, when you did not erase an element.
Note: If your intention is to get rid of the sBUFF_INFO element completely upon removal from the map, your programm shows a memory leak. Erasing the pointer from the map does not delete the pointed-to memory. You need to delete the pointee yourself (or use an appropriate smart pointer).
void CSkill::DecreaseAllBuffRemTime()
{
auto it = p_BuffInfo.begin();
while( it != p_BuffInfo.end() )
{
sBUFF_INFO* buff = it->second;
if(buff)
{
if(buff->dwTimeRemaining <= 0)
{
// probably delete buff too
it = p_BuffInfo.erase(it);
} else {
buff->dwTimeRemaining -= 2000;
++it;
}
} else {
++it;
}
}
}

How to erase an vector element in this situation?

I made a game, rambo shoots bullets and bullets hit zombies and I want to erase the zombie who got hit, from the zombie vector.
This nested loop checks collision between every zombie and bullet one by one. It works good for a while but when I start killing more, at some point, it crashes because it wants to use a function of erased zombie.
for ( it = zombies.begin(); it != zombies.end(); ++it ) {
it->attack();
for (rambo.it = rambo.bullets.begin(); rambo.it != rambo.bullets.end(); ++rambo.it) {
if(checkBasicCollision(it,rambo.it) && it != zombies.end()){
zombies.erase(it);
}
}
}
I've added it--; after zombies.erase(it); works better now but it still crashes sometimes.
I think its happening like, for example there are 5 zombies and 20 bullets, zombie iterator is at second zombie, and second zombie starts the bullet loop to check if it got hit. Loop starts, lets say third bullet hit the zombie, but loop is still going, even if zombie is erased, it still continues the loop.
I've added break; after zombies.erase(it); now it hasn't got any problem. But the code looks so dirty. Is there another way to erase the current element easily
While the solution for manually erasing was presented, note that it is not the most idiomatic one. In idiomatic C++ you would make use of the std::remove_if algorithm in the erase-remove idiom like so:
// 1. A predicate that check whether a zombie was it by any bullet:
auto is_zombie_hit = [&rambo](Zombie const& zombie) {
auto is_bullet_hitting_zombie = [&zombie](Bullet const& bullet) {
return checkBasicCollision(zombie, bullet);
};
return std::any_of(
rambo.bullets.begin(),
rambo.bullets.end(),
is_bullet_hitting_zombie
);
};
// 2. Use the erase-remove idiom:
zombies.erase(
std::remove_if(zombies.begin(), zombies.end(), is_zombie_hit),
zombies.end()
);
Note: yes, you can use lambda in-place, however I prefer naming them to indicate their role.
Note: this uses C++11, however replacing lambda with predicates is trivial and an implementation of any_of is easy enough to produce, much like all_of and none_of.
To use erase you need to use the returned value and assign it back to the iterator so it is valid for the next iteration.
for ( it = zombies.begin(); it != zombies.end(); ) {
it->attack();
for (rambo.it = rambo.bullets.begin(); rambo.it != rambo.bullets.end(); ++rambo.it) {
if(checkBasicCollision(it,rambo.it) && it != zombies.end()){
it = zombies.erase(it); // erase will increment the iterator
}
else{
++it; // no erase, increment the iterator manually
}
}
}
From the documetion for vector::erase the return value is:
An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.
When erasing vector elements, iterators and indices become invalidated. Also your code is incorrect for the case 2 or more bullets hit the same zombie (if it is possible). Because with the second bullet the inner loop will try to erase the zombie that was already hit. Instead, you should do it like this:
for ( uint i = 0; i < zombies.size(); ++i)
{
for( auto it = rambo.bullets.begin(); it != rambo.bullets.end(); ++it)
{
if(checkBasicCollision(zombies[i], it)
{
zombies.erase( zombies.begin() + i );
--i;
break; // zombie is dead (well, technically it was already dead)
// so no further checks are needed (i.e. exit inner loop)
}
}
}
Perhaps something like this:
auto zombie_tail = std::remove_if(zombies.begin(), zombies.end(), [&](Zombie const & zombie) {
zombie.attack();
return std::any_of(rambo.bullets.begin(), rambo.bullets.end(), [&](Bullet const & bullet) {
return checkBasicCollision(zombie, bullet);
});
});
zombies.erase(zombie_tail, zombies.end());
Alternatively, if you wanted to stay away from c++ algorithms:
for (it = zombies.begin(); it != zombies.end(); ) {
it->attack();
// Attempt to find a bullet that hit.
for(rambo.it = rambo.bullets.begin(); rambo.it != rambo.bullets.end(); ++rambo.it)
if (checkBasicCollision(it, rambo.it))
break;
// Possibly remove the zombie, and advance the iterator
if (rambo.it != rambo.bullets.end())
it = zombies.erase(it);
else
++it;
}
direct, easy to read and grasp, but maybe not very fancy;
for ( auto& z : zombies )
z.attack();
for( auto& b : rambo.bullets )
{
auto itr = zombies.begin();
while( itr != zombies.end() )
{
if( checkBasicCollision(b,*itr) )
itr = zombies.erase(itr);
else
++itr;
}
}
checkBasicCollision now takes references, not iterators

C++ Break out of a vector loop

I have a method in a class LinkRepository, I am checking for duplicate entries in the vector array Datalinks, which is a member of the class. I loop through all the elements in the array to check in the new entry Datalink* datalink already exist in the array. If so then don't add, just exit the loop.
void LinkRepository::SaveLink(Datalink* datalink) {
bool Exist = false;
for(vector<Datalink*>::iterator dl = Datalinks.begin(); dl != Datalinks.end(); ++dl)
{
if((strstr((*dl)->ParentID, datalink->ParentID) != NULL) && (strstr((*dl)->ChildID,datalink->ChildID) != NULL))
{
Exist = true;
dl = Datalinks.end();
}
}
if(!Exist)
{
Datalinks.push_back(datalink);
}
};
My program seems to crash on the next loop of the statement dl = Datalinks.end();
I have no idea why it is crashing?
Replace
dl = Datalinks.end();
With:
break;
To exit the loop
Here is a simple example to illustrate why your solution can't work:
int i = 0;
for (; i != 10; ++i)
{
i = 10;
}
This loop will never end because i will be incremented to 11 before comparison i != 10
It is crashing because first you set the iterator to Datalinks.end() and then, upon leaving this iteration, the for loop itself increments the iterator, making an invalid operation.
for(vector<Datalink*>::iterator dl = Datalinks.begin(); dl != Datalinks.end() && !Exist; ++dl)
{
if((strstr((*dl)->ParentID, datalink->ParentID) != NULL) && (strstr((*dl)->ChildID,datalink->ChildID) != NULL))
{
Exist = true;
}
}
Like everyone had said you are iterating one over. So, it's going into unwanted memory locations resulting in a seg fault eventually. You have to realize that the ++dl is happening at the end of the loop.
Also, using a break statement here is ridiculous. You already have a bool, make use of it.

What is proper way to delete objects that resides in a list that you find while looping that list?

I have a list of Star structs. These structs are in a std::list
I am double looping this list and compairing there locations to detect a collision. When A collision is found I will delete Star with the lowest mass. But how can I delete the Star when I am in the double Loop, and keep the loop going to check for more collisions?
It's worth mentioning that the second loop is a reverse loop.
Here is some code
void UniverseManager::CheckCollisions()
{
std::list<Star>::iterator iStar1;
std::list<Star>::reverse_iterator iStar2;
bool totalbreak = false;
for (iStar1 = mStars.begin(); iStar1 != mStars.end(); iStar1++)
{
for (iStar2 = mStars.rbegin(); iStar2 != mStars.rend(); iStar2++)
{
if (*iStar1 == *iStar2)
break;
Star &star1 = *iStar1;
Star &star2 = *iStar2;
if (CalculateDistance(star1.mLocation, star2.mLocation) < 10)
{
// collision
// get heaviest star
if (star1.mMass > star2.mMass)
{
star1.mMass += star2.mMass;
// I need to delete the star2 and keep looping;
}
else
{
star2.mMass += star1.mMass;
// I need to delete the star1 and keep looping;
}
}
}
}
}
You need to utilize the return value of the erase method like so.
iStar1 = mStars.erase(iStar1);
erase = true;
if (iStar1 == mStars.end())
break; //or handle the end condition
//continue to bottom of loop
if (!erase)
iStar1++; //you will need to move the incrementation of the iterator out of the loop declaration, because you need to make it not increment when an element is erased.
if you don't increment the iterator if an item is erased and check if you deleted the last element then you should be fine.
Since modifying the list invalidates the iterators (so that you cannot increment them), you have to keep safe the iterators before the list is changed.
In the most of the implementation std::list is a dual-linked list, hence a iteration like
for(auto i=list.begin(), ii; i!=list.end(); i=ii)
{
ii = i; ++ii; //ii now is next-of-i
// do stuff with i
// call list.erasee(i).
// i is now invalid, but ii is already the "next of i"
}
The safest way, is to create a list containing all the "collided", then iterate on the "collided" calling list.remove(*iterator_on_collided)
(but inefficient, since has O2 complexity)
You want to use the result of erase() to get the next iterator and advance the loop differently:
If you erase using the outer iterator you clearly can abondon checking this Star against others and break out of the inner loop. Only if the inner loop was complete you'd want to advance the outer iterator because otherwise it would be advanced by the erase().
If you erase using the inner loop you already advanced the iteration, otherwise, i.e. if no star was erased, you need to advance.
Sample code would look somethimg like this:
for (auto oit(s.begin()), end(s.end()); oit != end; )
{
auto iit(s.begin());
while (iit != end)
{
if (need_to_delete_outer)
{
oit = s.erase(oit);
break;
}
else if (need_to_delete_inner)
{
iit = s.erase(iit);
}
else
{
++iit;
}
}
if (iit == end)
{
++oit;
}
}