【问题标题】:Observing a runtime error while trying to run a code在尝试运行代码时观察到运行时错误
【发布时间】:2021-08-11 00:16:04
【问题描述】:

我在解决这个 leetcode 问题时遇到以下错误:

https://leetcode.com/problems/maximal-rectangle/

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

这是我的代码:

int area(vector<int> heights) {
    stack<int> s;
    int n = heights.size();
    int res = 0;
    for(int i = 0; i<n; i++) {
        while(!s.empty() && heights[s.top()] >= heights[i]) {
            int temp = s.top();
            s.pop();
            int a = heights[temp]*((s.empty()) ? (i) : (i-s.top()-1));
            res = max(res, a);
        }
        s.push(heights[i]);
    }
    while(!s.empty()) {
        int temp = s.top();
        s.pop();
        int a = heights[temp]*((s.empty()) ? (n) : (n-s.top()-1));
        if(a > res) res = a;
    }
    return res;
}
    
int maximalRectangle(vector<vector<char>>& matrix) {
    vector<int> heights;
    for(int i = 0; i<matrix[0].size(); i++) {
        heights[i] = (matrix[0][i] - '0');
    }
    int res = area(heights);
    for(int i = 1; i<matrix.size(); i++) {
        for(int j = 0; j<matrix[i].size(); j++) {
            if(matrix[i][j] == '0') heights[j] = 0;
            else heights[j] += 1;
        }
        res = max(res, area(heights));
    }
    return res;
}

请帮我找出我的错误。

【问题讨论】:

    标签: c++ function stack max


    【解决方案1】:

    函数maximalRectangle中的向量heights默认没有任何元素,所以你不能访问heights[i]

    你应该先分配足够的元素。您可以通过(例如)在构造函数中指定要分配的元素数量来分配元素。如果向量matrix的所有元素大小相同,可以是这样的:

    vector<int> heights(matrix[0].size());
    

    【讨论】:

    • 天啊!那真是个愚蠢的错误。感谢您指出!我现在无法忍受自己:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2014-05-13
    相关资源
    最近更新 更多