Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ code, Runtime error with heap buffer overflow

I tried writing a function that removes duplicates from an ordered array and returns the number of distinct duplicates. In fact, this is question 26 in leetcode. Here’s an inline link to leetcode.

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int n=0;
        int i=0;
        while(i<nums.size()){
            int j=i+1;
            while(nums[j]==nums[i]){
                j++;
            }
            nums[n]=nums[i];
            n++;
            i=j;
        }
        return n;
    }
};

I don’t know why this error happens, I hope you can help me find and resolve this runtime error, thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the while loop, you have while (nums[j] == nums[i]). However, you don’t actually check if j is a valid index of nums – i.e. if j doesn’t go outside the boundaries of nums. Therefore, j could possibly continuously increment until it accesses an element outside the boundaries of nums. Then, when nums[j] == nums[i] is checked, this causes a segmentation fault, which causes the heap buffer overflow.

Try something like

while (j < nums.size() && nums[j] == nums[i])

The code above will first check if j accesses an element outside nums. If it doesn’t, then it will check nums[j] == nums[i]. If it does, the while loop will automatically exit.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading