Segmentation fault (core dumped) - C++ Error

Viewed 89

I am trying to write a simple code of vector addition and I am getting this error. I don't know what it is. I am using VS Code in Ubuntu 18.04.

int main(){
    std::vector<int> vect1 = {1,2,3,4,5};
    std::vector<int> vect2 = {6,7,8,9,10};
    std::vector<int> vectsum;

    for (int i = 0; i < vect1.size(); i++){
        std::cout << vect1[i] << " ";
    }

    std::cout << std::endl;

    for (int j = 0; j < vect2.size(); j++){
        std::cout << vect2[j] << " ";
    }

    for(int i = 0; i < vect1.size(); i++){
        vectsum[i] = vect1[i] + vect2[i];
    }

    for (int i = 0; i < vectsum.size(); i++){
        std::cout << vectsum[i] << " ";
    }
    return 0;
}

Output:

1 2 3 4 5 
Segmentation fault (core dumped)
2 Answers

You haven't allocated any memory for vectsum (so you're hitting a NULL pointer when you assign a value to one of the elements)

std::vector<int> vectsum(5);

In the line vectsum[i] = vect1[i] + vect2[i]; you do not add an element to vectsum by subscripting the container. You are trying to access unallocated area of memory.

A straightforward solution can be of the following form:

for(int i = 0; i < vect1.size(); i++){
    // Allocate memory as needed
    vectsum.push_back(vect1[i] + vect2[i]);
}

You should also consider the following warning when using subscript:

warning: comparison of integer expressions of different signedness: 
‘int’ and ‘std::vector<int>::size_type’ {aka ‘long unsigned int’}

Which tells you not to mix signed and unsigned types.

Related