Adding two adjacent elements in a vector giving a segmentation fault for odd numbers (c++)

Viewed 110

I'm interested to understand why my C++ program is producing a segmentation fault. The task is to insert elements into a vector and to add the adjacent elements stored in such vector. The problem arises when there is an odd number of elements in the vector. I eventually got my program to work by changing idx != numbers.size() to idx < numbers.size() or idx <= numbers.size()-1. This allows the conditional statement for odd numbers to be passed and prints the last element instead of attempting an addition. Why does != not work in this instance and lead to the seg fault?

#include <iostream>
#include <vector>

using std::cout;
using std::cin;
using std::endl;
using std::vector;

int main(){
    vector<int> numbers = {1, 2, 3, 4, 5};
    int tmp;

    /*while(cin >> tmp){
        numbers.push_back(tmp);
    }*/

    for(decltype(numbers.size()) idx = 0; idx < numbers.size(); idx+=2){
        if((numbers.size() % 2 != 0) && (idx == numbers.size() - 1)){
            cout << numbers[idx] << endl;
        }
        else{
            cout << numbers[idx] + numbers[idx+1] << " ";
        }
    }

    cout << endl;

    return 0;
}
1 Answers

The reason "!=" does not work with an odd size vector is that idx starts at 0 and advances by two each time.

So consider your example where the vector has size 5.

idx will have values 0, 2, 4, 6, 8 and so on, but idx will never have the value 5 because idx will always be even. This will cause bad things, such as a segmentation fault, when idx is sufficiently large that numbers[idx] does not reference readable memory.

Use of < or <=, fixes the case of odd length, because in the case of an odd length l the loop will stop when idx reaches l+1.

Related