I am writing a program and there was a very subtle error that was hard to recognize.
I examined the program for hours and it looks like it's from my misuse of resize()
in allocating a new vector
in 2D vector
, from my misuse of back()
in vector
, or from updating a reference variable.
I wrote a simpler code that contains similar problem in my original program for demonstration:
int main() {
vector<vector<int>> A(1);
vector<int> &recent = A.back();
recent.emplace_back(50);
cout << A.back()[0] << endl; //prints 50
A.resize(2);
A[1] = vector<int>();
cout << A.size() << endl; //prints 2
recent = A.back();
cout << A[1].size() << endl; //prints 0
recent.emplace_back(20); //Segmentation fault occurs!!
cout << A[1][0] << endl;
}
Segmentation fault occurs when I tried to emplace_back(20)
, although in my original program it doesn't throw any error and doesn't emplace
the element either.
Possible cause of problem, in my opinion is:
- I used
resize()
to allocate a newvector
after the current last position of the 2D vectorA
, because I didn't know how toemplace_back()
an empty vector.
2, 3. In recent = A.back();
, I'm not sure if I am updating the reference variable(defined as vector<int> &recent
) correctly, and if back()
gives the correct reference to the newly allocated vector at the end of the 2D vector A
.
The logic looked perfectly fine, but obviously I am doing something wrong.
What am I doing wrong, and what can I do instead?