Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary search accessing out of range index

This is the code:

char binarySearch(unsigned int target, int* primes, unsigned int size){
    int* ptrToArray = primes;
    unsigned int first = 0;
    unsigned int last = size;

    while (first <= last){
        unsigned int middle = first + (last - first) / 2;
        printf("first: %d, last: %d, middle: %d\n", first, last , middle);

        if (ptrToArray[middle] == target){
            return 1;
        }

        if (ptrToArray[middle] < target){
            first = middle + 1;
        }else{
            last = middle - 1;
        }
    }
    return 0;
}

This is the output:

enter image description here

I've been staring at that peace of code for more than one should and still can't figure out where is the flaw.

like image 293
Ziezi Avatar asked Dec 24 '22 02:12

Ziezi


1 Answers

If middle is 0, as near the end of your debug output, the statement

last = middle - 1

causes an integer overflow; the conditions have to be reworked a bit.

like image 117
Codor Avatar answered Jan 07 '23 01:01

Codor