1

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.

Community
  • 1
  • 1
Yktula
  • 14,179
  • 14
  • 48
  • 71

1 Answers1

8
 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.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • 2
    Additionally, `vii[0][0]` "works" because the vector object in `vii[0]` did make sure the array would have an element at offset `0`, but the capacity is not required to survive the copy construction. – bitmask Mar 31 '13 at 17:22
  • 1
    @bitmask: I was editing to say about that simlutaneously with your comment! :) – Armen Tsirunyan Mar 31 '13 at 17:24
  • Sorry, I forgot the T; [Fastest Gun In The West](http://meta.stackexchange.com/a/19533/168610) – bitmask Mar 31 '13 at 19:17