Reputation: 33
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
Upvotes: 1
Views: 124
Reputation: 22910
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.
Upvotes: 0