ZioN
ZioN

Reputation: 560

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?

Upvotes: 1

Views: 3276

Answers (3)

Xibz
Xibz

Reputation: 366

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.

Upvotes: 0

twoflower
twoflower

Reputation: 6830

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.

Upvotes: 4

Andrew
Andrew

Reputation: 24846

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

Upvotes: 8

Related Questions