【问题标题】:AddressSanitizer: heap-buffer-overflow on address 0x6020000000b4 at pc 0x0000003a86fc bp 0x7ffeebd5f9d0 sp 0x7ffeebd5f9c8AddressSanitizer:堆缓冲区溢出地址 0x6020000000b4 在 pc 0x0000003a86fc bp 0x7ffeebd5f9d0 sp 0x7ffeebd5f9c8
【发布时间】:2020-11-01 13:55:36
【问题描述】:

尝试解决 leetcode 上的问题,但我一直收到错误消息:

==29==错误: AddressSanitizer: heap-buffer-overflow on address 0x6020000000b4 at pc 0x0000003a86fc bp 0x7ffeebd5f9d0 sp 0x7ffeebd5f9c8 在 0x6020000000b4 线程 T0 处读取大小为 4

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        int size = arr.size();
        int freq = 0;
        vector<int> count;
        for(int i=0; i<size;i++){
            freq = std::count(arr.begin(), arr.end(), arr[i]);
    
        }
        count.push_back(freq);
        int a = count [0];
        for(int i = 0; i < count.size();i++){
            if(count[i] == (count[i+1])){
                return false;
            }
        }
        return true;
    }
  
};

不确定问题是什么,任何见解将不胜感激。提前谢谢!

【问题讨论】:

  • i &lt; count.size()count[i+1]。考虑icount.size() - 1 时的最终迭代。

标签: c++


【解决方案1】:

for(int i = 0; i < count.size();i++){
    if(count[i] == (count[i+1])){
        return false;
    }
}

i 将到达 count.size()-1 并且 count[i+1] 变为 count[count.size()-1+1]count[count.size()] 并且超出范围。

编写此循环的更好方法是

for(int i = 1; i < count.size(); i++){
    if(count[i-1] == (count[i])){
        return false;
    }
}

它稍后开始一个并且迭代更少一个。如果 count 中的元素少于 2 个,则退出条件会阻止循环进入,从而使缓冲区不可能下溢。

注意:这个答案没有考虑算法的正确性。

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 2019-01-05
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2021-06-13
    • 2010-11-11
    相关资源
    最近更新 更多