Search code examples
c++stdvectorassignment-operatorcopy-assignment

Why doesn't this vector assignment work?


Similar Questions:


#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<vector<int> > vvi;
  vvi.resize(1);
  vvi[0].reserve(1);
  vvi[0][0] = 1;

  vector<int> vi = vvi[0];

  cout << vi[0]; // cout << vvi[0][0]; works

  return 0;
}

This gives me a seg fault, and I can't tell why.


Solution

  •  vvi[0].reserve(1);
     vvi[0][0] = 1;
    

    You need resize, not reserve.

    Accessng an element i where i>=v.size() is undefined behavior. reserve affects capacity, not size.

    If I were to go into the practical aspect, I might speculate that perhaps you might get away with the assignment vvi[0][0] = 1; (in Release Mode, at least). But the main practical problem lies here

    vector<int> vi = vvi[0];
    

    The problem is that vvi[0]'s size is 0, so vi's internal array size is 0, regardless of vvi[0]'s capacity. That's I think where you get the seg fault, after you

    cout << vi[0]; // cout << vvi[0][0]; works
    

    But that's all speculations. The correct answer to your question is that this

    vvi[0].reserve(1);
    vvi[0][0] = 1;
    

    already has undefined behavior, and no further considerations are required.