简体   繁体   中英

heap-buffer-overflow on 3Sum implementation

I'm new to c++ and I'm trying to resolve the problem of 3Sum in LeetCode. However, I can't deal with this error which is called "heap-buffer-overflow".

vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> res;
    int numslen = nums.size();
    sort(nums.begin(), nums.end());
    int i = 0;
    while(i < numslen - 2){
        int start = i + 1;
        int end = numslen - 1;
        while (start < end) {
            if (nums[i] + nums[start] + nums[end] == 0) {
                res.push_back({ nums[i], nums[start], nums[end] });
                end--;
                while (nums[end] == nums[end+1]) { end--;   }
            }
            else if (nums[i] + nums[start] + nums[end] > 0) { end--; }
            else { start++; }
        }
        i++;
        while (nums[i] == nums[i - 1]) { i++;   }
    }   
    return res;
}

This is the error message.

AddressSanitizer: heap-buffer-overflow on address 0x60200000044c at pc 0x000000406c74 bp 0x7ffd2a1cd0d0 sp 0x7ffd2a1cd0c8
while (nums[i] == nums[i - 1]) { i++;}

should be

while (i < numslen && nums[i] == nums[i - 1]) { i++;}

The first time the loop above is executed, i and i-1 are guaranteed to be within range. But what if the nums have trailing duplicate numbers ? Your version will read "forever" on invalid memory.

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