Thread: Introductions and Iterators

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    I think you're accessing memory that is no longer yours. When you erase() an element, the new end() moves one to the left and marks the end of your allowed memory. That means the old end() is now two past the end, so between the old end and the new end there is one block of memory that is not yours. The vector probably doesn't reallocate by creating a smaller array, copy the elements into it, and release the current memory, so the block of memory between the new end and the old end is probably still reserved for the vector, but by continuing on until you hit the old end(), you are iterating over memory that isn't part of the allowed memory for the current vector.

    I can't get it to crash with strings in the vector, but with ints in the vector, the following crashes(no matter how you handle the interator after calling erase() ):
    Code:
    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
    	
    	vector<int> v;
    	v.push_back(1);
    	v.push_back(2);
    	
    
    	vector<int>::iterator iter = v.begin();
    	vector<int>::iterator end = v.end();
    	
    	int counter = 0;
    	while(iter != end)
    	{
    
    		if(*iter == 2)
    		{
    			v.erase(iter);
    		}
    		else
    		{
    			++iter;
    		}
    		
    		cout<<counter<<endl;
    		++counter;
    	}
    
    	
    	return 0;
    }
    Last edited by 7stud; 01-16-2007 at 08:03 AM.

Popular pages Recent additions subscribe to a feed