Reputation: 1
//this is my code that i have written
vector<vector<int>> generate(int numRows) {
vector<vector<int>>ans;
ans[0].push_back(1);
if(numRows==1) return ans;
ans[1].push_back(1);
ans[1].push_back(1);
if(numRows==2) return ans;
for(int i=2;i<=numRows-1;i++){
for(int j=0 ; j<= ans [i] . size() - 2 ; j++){
int x= ans [i][j] + ans [i][j+1];
ans [i+1].push_back(x);
}
ans [i+1].insert(ans [i+1].begin(),1);
ans [i+1].insert(ans [i+1].end(),1);
}
return ans;
}
this code showing below error.
Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
Upvotes: 0
Views: 1018
Reputation: 1409
As vector
stores data on heap internally which can grow and shrink based on your usage. But in your case, you made an empty vector
so it did not allocate any memory. To avoid this error you have to provide size to vector constructor or push back empty vector on every index you want to use.
so you might want to do this:
std::vector<vector<int>> ans(numRows);
ans[0].push_back(1);
This will work.
Upvotes: 1