1

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
2
  • 1
    Watch out for overstepping the bounds with i and end. Suppose, for instance, that your input is a vector with three identical numbers... Commented May 17, 2019 at 12:06
  • And please show us how you called this function when you got that error! Commented May 17, 2019 at 12:08

1 Answer 1

0
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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your anwser. But there is another bug I just found that can also make this wrong message. while (nums[end] == nums[end+1]) { end--;} should be while (start < end && nums[end] == nums[end+1]) { end--;}.
@KongJohn I am getting no error when I run your code for a small vector. Could you please show us how you call the function (specially the input vector)?
@KongJohn yes both are similar.
@AKL You can try following code:vector<vector<int>> res; vector<int> nums = {0,0,0}; res = threeSum(nums);, and you will realize the bug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.