简体   繁体   中英

C++ errror: Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer:

I am working on LeetCode question 6280 and get the following error:

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

Here is my code:

class Solution {
public:
    vector<int> closestPrimes(int left, int right) {
        vector<int> prime_list;
        for (int i = left; i <= right; i++) {
            if (isPrime(i))
                prime_list.push_back(i);
        }
        
        vector<int> res;
        res[0] = -1;
        res[1] = -1;
            
        if (prime_list.size() < 2) return res;
        
        int min_dist = prime_list[1] - prime_list[0];
        res[0] = 0;
        res[1] = 1;
        for (int i = 1; i < prime_list.size(); i++) {
            if (prime_list[i] - prime_list[i-1] < min_dist){
                res[0] = i - 1;
                res[1] = i;
            }
        }
        return res;
    }
    
    bool isPrime(int n) {
        if (n <= 1) return false;
        
        for (int i = 2; i < sqrt(n) + 1; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }
    
};

Could anyone help what's the problem? Thank you!

In C++ std::vector don't work like that:

        vector<int> res;
        res[0] = -1;
        res[1] = -1;

When you declared variable res it holds empty vector, accessing any elemnt of it is undefined behavior. You need first add these elements. Either by constructing vector of appropriate size, resizing it or, preferably, by appending values into it:

        vector<int> res;
        res.push_back(-1);
        res.push_back(-1);

Also if you know size of your data when you writing program and it will be fixed, better approach will be to use std::array . In this case your code will work as expected:

        std::array<int, 2> res;
        res[0] = -1;
        res[1] = -1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM