C++ Segmentation Fault when Iterating through a Vector

Posted by user1790374 on Stack Overflow See other posts from Stack Overflow or by user1790374
Published on 2012-11-01T04:59:26Z Indexed on 2012/11/01 4:59 UTC
Read the original article Hit count: 116

Filed under:
|
|
|

I have a program that maintains an integer vector. I have three functions that add an integer, remove an integer and check whether an integer is already in the vector. The problem is with the last one.

vector<int> children;
void CtpTestingApplication::addChild(int child)
{
    for (int i=0; i<children.size(); i++)
    {
    //already a child
    if (children[i]==child)
        return;
    }
    //child not yet recorded
   children.push_back(child);
   received.push_back(false);   
   cout<<"added child "<<child;
}

void CtpTestingApplication::removeChild(int child)
{
   Enter_Method("removeChild");
   for (int i=0; i<children.size(); i++)
   {
    //already a child, remove it
    if (children[i]==child)
    {
        children.erase(children.begin()+i);
        received.erase(received.begin()+i);
        cout<<"removed child "<<child;
    }
   } 
   //not recorded, no need to remove
}

bool CtpTestingApplication::isChild(int child)
{
   Enter_Method("isChild");
   vector<int>::iterator ic;
   bool result = false;
   for (ic= children.begin(); ic < children.end(); ic++)
   {
     cout<<*ic<<" vs "<<child;
  //     if (child==*ic)
         result = true;
   }
   return result;
}

I always get segmentation fault when I uncomment "if (child==*ic)", even though printouts show that the vector is not empty and contains the expected integers.

For example, with the if statements commented, I can see 1 vs 4, 2 vs 4, 4 vs 4, 12 vs 4

I also attempted looping using children[i] and so on, but to no avail. Any help would be appreciated. Thank you.

© Stack Overflow or respective owner

Related posts about c++

Related posts about vector