Search code examples
c++vectorstdvector

C++ Segmentation fault core dumped for simple vector operation


I have the following code c++ code

#include <vector>
#include <iostream>

using namespace std;

#define for_loop(upper_bound) for (int i=0;i<upper_bound; ++i)

// #define SHOW_VECTOR(vec_in) for(int j=0;j<vec_in.size();j++){ cout << vec_in[j] << " " << endl;};


int main(){
    int dim_1=10;
    int dim_2=3;

    int outer_i;
    // vector variable declared here to have 10 values
    vector<vector<int>>vec_var(dim_1);

    for_loop(dim_1){
        outer_i = i;
        for_loop(dim_2){
            cout << outer_i << " " << i << endl;

            vec_var[outer_i][i]=103;    
        }
    }

    return 0;
}

When I try and run it i get the following error:

Segmentation fault (core dumped)


Solution

  • You need to size both your outer and inner vectors

    vector<vector<int>> vec_var(dim_1, vector<int>(dim_2));
    //                                 ^ inner vector default size
    

    Otherwise as written, you have an outer vector if size dim_1 but all of the inner vectors are empty.

    As an aside, since I notice you then filling the vector with constant values, you can do all that in one step too

    vector<vector<int>> vec_var(dim_1, vector<int>(dim_2, 103));
    //                                                    ^ default of inner vector elements