I am having a problem with this code on Leetcode. In there , I am solving a problem to remove duplicates in an array but I am getting heap buffer overflow error -
Here's the code -
int removeDuplicates(int* nums, int numsSize) {
int i,j,temp,k=0,num = *(nums+numsSize-1);
for(i = 0;i<numsSize;i++){
if(*(nums+i) == *(nums+i+1)){
if(num != *(nums+i)){
k++;
}
for(j = i+1;j<numsSize;j++){
temp = *(nums+j);
*(nums+j) = *(nums+j+1);
*(nums+j+1) = temp;
}
num = *(nums+i);
i--;
}
}
return k;
}
I want to know what causing this error and how to solve it?
First of all, for the sake of readability get rid of all access in the form of
*(nums+i)and replace it withnums[i].At the last iteration of the loop,
if(*(nums+i) == *(nums+i+1)){will overflow, becausenums+i+1is then equivalent tonums + numsSize-1 + 1which is one item out of bounds.You can solve this by for example doing
for(i = 1; i<numsSize; i++){and thenif(nums[i-1] == nums[i]).Same issue with
*(nums+j+1);.