Search code examples
c++arraysvectorgraph

Declaring 2D Vector in Global Scope gives segmentation fault


#include <bits/stdc++.h>

using namespace std;

int n;
std::vector<bool> visited(n,false);
std::vector<std::vector<int>> g(n,std::vector<int>(n));


int main() {
    cin>>n;
    //std::vector<std::vector<int>> g(n,std::vector<int>(n));
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            cin>>g[i][j];
        }
    }
    cout<<g[0][0];

}

2D vector declared inside main function gives no error but when declared in global scope gives SIGSEV error


Solution

  • When visited and g get initialized, the value of n is 0. (n is declared in global namespace and will be zero-initialized.) So the vectors are empty and contain no elements. Then access to them like g[0][0] leads to UB.

    On the other hand, for the vector g declared in main(), n is set to some value and then used to initialize g, then g is initialized as containing n elements.