c - Binary search accessing out of range index -


this 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 output:

enter image description here

i've been staring @ peace of code more 1 should , still can't figure out flaw.

if middle 0, near end of debug output, statement

last = middle - 1 

causes integer overflow; conditions have reworked bit.


Comments