1

I want to erase an element from a vector in c++, but it shows a runtime assertion error.

My code is:

   int i=0;
        for(socketIterator=vectClientSocket.begin();socketIterator!=vectClientSocket.end();){
            SOCKET clientSocket=*socketIterator;

            isTrue=getBufferData(strt,stp,rm,clientSocket);
            if(!isTrue){
                vectClientSocket.erase(vectClientSocket.begin()+i);

                vector<RMLObserver*>::iterator it;
                for(it=vectRMLObserver.begin();it<vectRMLObserver.end();it++)
                {
                    RMLObserver *observer = (RMLObserver*)*it;
                    observer->infosetSent(info->getRMLThinTranskportToken());
                }
            }
            else
                ++socketIterator;

            i++;
        }

When one element is removed it shows a runtime error,

enter image description here

Please help me...thank you in advance.

yogesh patel
  • 375
  • 3
  • 9
  • 20
  • See http://stackoverflow.com/questions/4645705/vector-erase-iterator/4645758#4645758 – Roland Illig Aug 24 '11 at 06:40
  • I suggest you to use while loop instead of for loop 'while( !vec.end())'. Get the first element of the vector and erase it! – sarat Aug 24 '11 at 07:04

2 Answers2

2

You need to update your iterator after erasing an element:

socketIterator = vectClientSocket.erase(socketIterator);

see also std::vector<..>::erase(..) documentation

[EDIT]

Use the operator !=(..) to compare the iterators:

for(socketIterator=vectClientSocket.begin();socketIterator!=vectClientSocket.end();){
Simon
  • 1,496
  • 8
  • 11
  • i change my code and use !=() to compare but still same error. – yogesh patel Aug 24 '11 at 06:48
  • @yogesh, you've updated you code with the second fix than Simon said, but you haven't used the first fix he said. The first fix is the one that is really causing your bug. Do it like this `socketIterator = vectClientSocket.erase(socketIterator);`. – john Aug 24 '11 at 08:32
1

After this line:

 vectClientSocket.erase(socketIterator);

socketIterator is an invalid iterator because where it used to point has been erase. Between this line and the next iteration through your loop you never give it a valid value so this line in the next iteration is an invalid dereference.

SOCKET clientSocket=*socketIterator;

As Simon points out, even before this, the loop condition socketIterator<vectClientSocket.end() will also cause undefined behavior as socketIterator is no longer a valid iterator into vectClientSocket.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • 1
    Not only dereferencing the iterator also checking the loop condition is a problem. – Simon Aug 24 '11 at 06:39
  • @Simon: Good point. In fact looking at the exact error this is the more likely point at which the assert fires. – CB Bailey Aug 24 '11 at 06:40