简体   繁体   中英

AddressSanitizer: heap-buffer-overflow on address 0x6020000000b4 at pc 0x0000003a86fc bp 0x7ffeebd5f9d0 sp 0x7ffeebd5f9c8

Trying to solve a problem on leetcode and I keep getting an error saying:

==29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000000b4 at pc 0x0000003a86fc bp 0x7ffeebd5f9d0 sp 0x7ffeebd5f9c8 READ of size 4 at 0x6020000000b4 thread T0

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;
    }
  
};

Not sure what the issue is, any insights will be greatly appreciated. Thank you in advance!

In

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

i will reach count.size()-1 and count[i+1] becomes count[count.size()-1+1] which is count[count.size()] and out of range.

A better way to write this loop is

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

It starts one later and iterates one less. The exit condition prevents the loop from ever entering if there are less than 2 elements in count making underflowing the buffer impossible.

Note: This answer does not take into account the correctness of the algorithm.

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