[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: g++



On Tue, Apr 23, 2002 at 09:19:37AM +0400, Andrew Saunders wrote:
>    void f()
>    {
> 
>         vector<string> paths;
>         paths.push_back("1");
> 
>         cout << "loop..." << endl;
> 
>         vector<string>::iterator p = paths.begin();
>         while (p != paths.end()) {
>                 cout << "\t" << *p << endl;
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
		  actually your segfault is here!!!

>                 
>                 paths.push_back(p, "2");
>                 ^^^^^^^^^^^^^^^^^^^^^^^^
>                 this is the place of segfault
>                 
>                 ++p;
>         }
>                 
>         cout << "end..." << endl;
>    }

After the paths.push_back() your iterator became invalid. You can do,
in this case, without modifing the funcionality, 
p= paths.insert(paths.end(), "2");
but this will loop forever. Notice that even with this command your
iterator will became invalid, so you must pass the return of the
insert() to it. And you will have to have another stop condition
for the loop.

When you did the paths.push_back() the container have been resized,
and possibly changed position on memory, so your iterator became
invalid. If you put, after the first paths.push_back("1")
paths.reserve(10)
your program won`t segfalt until paths.size()== 10, but it will
segfault after that becouse the container will need to be
resized.

HTH,
  Rafael Sasaki


-- 
To UNSUBSCRIBE, email to debian-gcc-request@lists.debian.org
with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org



Reply to: