Global vector causing a segfault at end of c++ program

Viewed 201

This program prints out "bye" at the very end and then segfaults. I have no idea why. I think it might have something to do with the global vector? I've played around with it and discovered that if I take away the cout << i,j and the cout << endl, it will segfault without printing anything. n,p,k, and T aren't very big, at most 30.

    int n, p, k;
    vector<vector<int>> plates;

    int main() {
      int T;
      cin >> T;
      for (int t = 1; t != 1 + T; ++t) {
        cin >> n >> k >> p;
        plates.resize(n + 1, vector<int>(k + 1, 0));
        for (int i = 1; i <= n; ++i) {
          for (int j = 1; j <= k; ++j) {
            cin >> plates[i][j];
            cout << i << "," << j << "\t";
          }
          cout << endl;
        }
      }
      cout << "bye" << endl;
    }
1 Answers
plates.resize(n + 1, vector<int>(k + 1, 0));

resize() does not do what you think it does. resize() does not set every value in the resized vector to the 2nd parameter, here. Only new values in the vector, if it grows, are set to this value.

So, if on the first time through the outer loop the vector was 2 rows by 2 columns, and the second time through the outer loop the dimensions are specified as 50x50, this will add 48 more values to plates, which each value being a vector with 50 values.

But the first two values in plates vector remain unchanged, with their original two-valued vector in them.

The solution seems to be obvious: add plates.clear() before this resize().

Related