segmentation fault

Here's a portion of my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void chain(int number)
{
    unsigned int i;
    int element;
    std::vector<int>chain2;
    for(i=0;i<chain1.size();i++)
    {
        if(number==chain1[i])
            return;
    }
    element=number;
    do
    {
        chain2.push_back(element);
        element--;
    }
    while(element!=chain1.back());
    for(i=chain2.size()-1;i>=0;i--)
        chain1.push_back(chain2[i]);
}


This is the body of one of my functions. chain1 is an integer vector I declared globally and the purpose of the function is to check to see whether the number sent as an argument is in chain1 or not, and if not, it subtracts and stores successive numbers in chain2 until the number equals the last element in chain1. Then it appends the elements of chain2 onto chain1 in reverse order.

For example, say that chain1={1,2,3,4} and the number 8 is sent to the function. Then the function will change it to chain1={1,2,3,4,5,6,7,8}. But if the number 3 had been sent instead, no changes would be made.

When I debug the code, I get a segmentation fault at line 19. Any ideas why?
Last edited on
When i == 0, your for loop is subtracting from i again, and you can't access an index of -1!
If chain1 is empty you are not allowed to call chain1.back() as you do on line 17, so the function will not work if chain1 is empty.

On line 18, i is unsigned so i>=0 can never be false. The loop will run forever and it should not be hard to see why that goes wrong. You could change the loop to for(i=chain2.size()-1;i<chain2.size();i--) but using iterators might be a better idea.
Thanks Peter. chain1 wasn't empty. the problem was that i was unsigned. So to fix it I just declared i as a normal, signed integer int i; and then for line 6 I just type cast i as unsigned.
Last edited on
Topic archived. No new replies allowed.