首页 > 解决方案 > 运行时错误:引用绑定到“int”类型的空指针(stl_vector.h):LeetoCode 907

问题描述

我正在尝试 907. Leetcode 上的子数组最小值之和。

我不断收到此错误:

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

这是我尝试过的(我知道这很天真,很可能会 TLE,但我也想知道什么是错误的,以至于它不起作用):-

class Solution {
public:
    int sumSubarrayMins(vector<int>& arr) {
        vector<int> ans;
        int sum =0; 
        int mn=0;
        int m = 1000000007;
        int n = arr.size();
        for(int i = 0 ; i<n; i++){
            for(int j = i; j<n; j++){
                for(int k = i; k<j; k++){
                    ans.push_back(arr[k]);
                }
                sort(ans.begin(), ans.end());
                mn = ans[0];
                sum = sum + mn;
                ans.clear();
            }
        }
        return sum%m;
    }
};

怎么了?

标签: c++runtime-error

解决方案


在第一次迭代中,

  • ans没有元素
  • i = 0
  • j = i( j = 0)

然后不会推送任何元素,ans因为i < j它是假的。

因此,mn = ans[0];超出范围访问无效,因为ans仍然没有元素。


推荐阅读