I'm getting a runtime error for the below code while solving the Pascal's triangle question on Leetcode:
Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior
I did come up with other code that works, but I'd like to know why I'm getting the error for this code.
vector<vector<int>> generate(int numRows) {
vector<vector<int>> v(numRows);
vector<int> q;
for(int i=0;i<numRows;i ){
q.resize(i 1);
q[0]=q[i]=1;
for(int j=1;j<i;j ){
q[j]=v[i-1][j-1] v[i-1][j];
}
v.push_back(q);
q.clear();
}
return v;
}
CodePudding user response:
You construct vector v with numRows number of elements. And then you iterate from 0 to numRows - 1 and in each iteration, you add a new vector to the and of vector v, so you end up with a vector holding 2 * numRows number of elements instead of numRows number of elements.
Instead of vector<vector<int>> v(numRows); you should use v.reserve(numRows). Here is full code:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> v;
v.reserve(numRows);
vector<int> q;
for(int i=0;i<numRows;i ){
q.resize(i 1);
q[0]=q[i]=1;
for(int j=1;j<i;j ){
q[j]=v[i-1][j-1] v[i-1][j];
}
v.push_back(q);
q.clear();
}
return v;
}
