0

Observing a runtime error when trying to run the below code !!

Line 1034: Char 9: runtime error: reference binding to null pointer of type '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

#include <algorithm>
#include <climits>
#include <vector>
class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        vector< vector<int> >  soln(1000, vector<int>(0)) ;
        vector< vector<int> >  index(1000, vector<int>(0)) ;
        int ans = INT_MIN ;
        int tmp = 0;
        int ind = 0;
        soln[0][0]=triangle[0][0];
        index[0][0]=0;
        int triangle_size = int(triangle.size());
        for (int i = 1 ; i < triangle_size ; i++) {
            int soln_size = int(soln[i-1].size());
            for (int j = 0; j < soln_size ; j=j+2) {
                ind = index[i-1][j];
                tmp = soln[i-1][j] + triangle[i][ind];
                if (tmp > ans) {
                    ans=tmp;
                }
                soln[i][j] = tmp;
                index[i][j] = ind;
                tmp = soln[i-1][j] + triangle[i][ind+1];
                if (tmp > ans) {
                    ans=tmp;
                }
                soln[i][j+1] = tmp;
                index[i][j+1] = ind+1;            
            }
        }
        return ans;
    }
};

1 Answer 1

1
    int minimumTotal(vector<vector<int> > &triangle) {
        vector< vector<int> >  soln(1000, vector<int>(0)) ;
        vector< vector<int> >  index(1000, vector<int>(0)) ;
        int ans = INT_MIN ;
        int tmp = 0;
        int ind = 0;
 >>>>   soln[0][0]=triangle[0][0]
 >>>>   index[0][0]=0;

Here. soln is a vector of 1000 vector of size 0, soln[0] is a vector of size 0, so soln[0][0] is out of range. Accessing it is a UB.

Sign up to request clarification or add additional context in comments.

1 Comment

If you want to create a vector contains one zero, then it is std::vector<int> a{0}; instead of std::vector<int> a(0);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.