Search code examples
calgorithmrecursionbinary-searchfunction-definition

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

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.