LeetCode运行报错: reference binding to null pointer of type 'value_type'

在LeetCode做题的过程中,遇到"reference binding to null pointer of type ‘value_type’" 这个问题,现在对这个问题进行一下分析和总结。

产生原因:

1.对于一些stl和一些数据结构掌握不准确。
2.忽视判断条件。

错误种类:

1.测试样例输入为非空数组情况:

Runtime Error Message:
reference binding to null pointer of type 'value_type'
Last executed input:
[1]
Runtime Error Message:reference binding to null pointer of type 'value_type'
Last executed input:[[1,1,1],[1,0,1],[1,1,1]]

可能原因:
a.数组越界,在对vector初始化的时候没有初始化到合适大小,而在接下来的使用中使用了越界的下标。
例:

class Solution {
public:
    int maxProfit(vector<int>& nums) {
        int len = prices.size();
        vector<int> sold(len - 1, 0); // 初始化长度为len - 1
        for (int i = 1; i < len; i++) {
            sold[i] = 1; // 越界
        }
        return sold[len - 1]; // 访问越界
    }
};

二维数组初始化例子2:

法一:
vector<vector<int>>vis(m, vector<int>(n, 0));

法二:
vector<vector<bool>> visited(rows);// 这里要进行初始化
for (int i = 0;  i < visited.size(); i++) 
    visited[i].resize(cols); // 这里也要进行初始化
for(int i=0;i<visited.size();++i){
    for(int j=0;j<visited[0].size();++j){
        visited[i][j] = false;
    }
}

b.对于vector构建出来的二维数组没有进行空间的申请,比如有些返回类型为vector<vector<>>类型的函数,对于这个返回值vector表示的二维数组要先申请大小,否则使用下标访问就会报这类错误。
例:

vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
    vector<vector<int>> res(M.size()); // 这里要进行初始化
    for (int i = 0;  i < res.size(); i++) res[i].resize(M[0].size()); // 这里也要进行初始化
    for (int i = 0; i <  M.size(); i++) {
        for (int j = 0; j < M[0].size(); j++) {
            res[i][j] = 1;
        }
    }
    return res;
}

2.测试样例输入为空数组情况:

Runtime Error Message:reference binding to null pointer of type 'value_type'
Last executed input:[]

可能原因:
对于数组长度为0的情况没有进行判断,加入判断条件就可以解决。

总结

这类错误多数是因为在编程的过程中由于一些判断或者初始化细节没有考虑到,解决起来很简单,但是也容易让人忽视。

原文链接:https://blog.csdn.net/m0_38088298/article/details/79249044

原文地址:https://www.cnblogs.com/dindin1995/p/13059079.html