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

AddressSanitizer: DEADLYSIGNAL

I cannot figure out the cause of this error.

int binarySearch(int* arr,int l,int r,int x){
    int mid = (l+r)/2;
    if(arr[mid]==x){
        return mid;
    }
    else if(arr[mid]>x){
        binarySearch(arr,mid,r,x);
    }
    else if(arr[mid]<x){
        binarySearch(arr,l,mid,x);
    }
    else{
        return -1;
    }
    return 0;
}
int search(int* nums, int numsSize, int target){
    return binarySearch(nums,0,numsSize-1,target);
}

This is simple binary search program.
This is the error.

==30==ERROR: AddressSanitizer: stack-overflow on address 0x7ffdbdd5cff8 (pc 0x55745fa9be6c bp 0x7ffdbdd5d010 sp 0x7ffdbdd5d000 T0)
==30==ABORTING

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 :

For starters i t seems due to a typo the first function parameter has an incorrect type. The function should be declared at least like

int binarySearch( const int arr[], int l, int r, int x );

The function does not stop to call itself recursively if the target element is not equal to an element in the array.

Also if arr[mid] is greater than x then all values in the range [mid, r] obviously also will be greater than x. So the sub-statement of the of statement

else if(arr[mid]>x){
    binarySearch(arr,mid,r,x);
}

is incorrect,

Using your approach the function definition can look the following way

int binarySearch( const int arr[], int l, int r, int x )
{
    if ( !( r < l ) )
    {
        int mid = l + ( r - l ) / 2;

        if( arr[mid] == x )
        {
            return mid;
        }
        else if ( x < arr[mid] )
        {
            return binarySearch( arr, l, mid - 1, x );
        }
        else
        {
            return binarySearch( arr, mid + 1, r, x );
        }
    }

    return -1;
}

Pay attention to that the searched array must be sorted.

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