Thread: Known STL bug?

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218

    Known STL bug?

    Just wanted to know if the following program has a known STL bug. The program crashes with both VS 6, VS.Net 2002 and MingW Developer Studio. Here is the program:
    Code:
    #include <vector>
    
    int main(int argc, char **argv) 
    {
    	std::vector<int> vec;
    	vec.push_back(10);
    	//vec.push_back(20);
    	std::vector<int>::iterator iter;
    	for(iter=vec.begin(); iter!=vec.end();iter++)
    		iter = vec.erase(iter);
    }
    If you uncomment the second push_back it works fine though.

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Code:
    	for(iter=vec.begin(); iter!=vec.end();iter++)
    		iter = vec.erase(iter);
    is equivalent to:
    Code:
    iter = vec.begin();
    while (iter != vec.end())
    {
        iter = vec.erase(iter);
        iter++;
    }
    Let's see what happens with one item in the vector:
    Code:
    iter = vec.begin();
    while (iter != vec.end())
    {
        iter = vec.erase(iter); /* Returns vec.end() */
        iter++; /* Moves to vec.end() + 1 */
    
        /* Loop will not stop as we are at vec.end() + 1, therefore we will crash. */
    }
    and with two items:
    Code:
    iter = vec.begin();
    while (iter != vec.end())
    {
        iter = vec.erase(iter); /* Returns vec.end() - 1 (second item in vec) */
        iter++; /* Moves to vec.end() */
    
        /* Loop will stop as we are at vec.end(), but not every item will be deleted. */
    }
    In fact, the code will crash with if vec has an odd number of items and not crash if vec has an even number of items.

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    ah! that makes sense, thanks for clearing this up.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Formatting Using STL
    By ChadJohnson in forum C++ Programming
    Replies: 4
    Last Post: 11-18-2004, 05:52 PM
  2. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  3. STL or no STL
    By codec in forum C++ Programming
    Replies: 7
    Last Post: 04-12-2004, 02:36 PM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM