I am getting this ERROR: AddressSanitizer: negative-size-param: (size=-8)

1.6k Views Asked by At

When removing the given elements from the given array, I keep getting an error.

This is my code, I am not sure where I the error is:

int removeElement(vector<int>& nums, int val) {
        int i=0;
        int size=nums.size();
        if(size <=0){
            return 0;
        }
        for(int x : nums){
            if(x==val){
                nums.erase(nums.begin() + i );
            }
            i=i+1;   
        }
        int size1=nums.size();
        return size1;
    }

I then receive this error:

=================================================================
==33==ERROR: AddressSanitizer: negative-size-param: (size=-8)
    #8 0x7f3d479c882f  (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
0x603000000060 is located 0 bytes to the right of 32-byte region [0x603000000040,0x603000000060)
allocated by thread T0 here:
    #6 0x7f3d479c882f  (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
==33==ABORTING
1

There are 1 best solutions below

4
On

This loop:

for(int x : nums){

Is syntactic sugar that loops over the vector using iterators.

nums.erase(nums.begin() + i );

This invalidates the current iterator (and iterators to elements right of current element). Using the iterator such as for example incrementing it causes undefined behaviour.

The current iterator is incremented once the end of the loop body is reached. The behaviour of the program is undefined.


What you need to do is to use std::remove_if to move the remaining elements to the beginning of the vector, and then erase the elements at the end (that were moved from) using the overload that accepts a pair of iterators. This is called the erase-remove idiom.