简体   繁体   中英

Binary search algorithm in c

I'm trying to create a function int find_pos(int item, int a[], int len) that works as follows:

Returns the index in array of the key t that is the the successor of k , if one exists, else return KEY_NOT_FOUND .

Key t is the successor of k , if t is the smallest key stored in sda->buffer such that t >= k .

const int KEY_NOT_FOUND = -1;

int find_pos(int item, int a[], int len) {
 int low = 0;
 int high = len-1;
 if (a[0] >= item && len == 1) {
 return 0;
 }
 if(a[0] < item && len == 1) {
 return KEY_NOT_FOUND;
 }
 while (low <= high) {
 int mid = low + (high - low) / 2;
 if (a[mid] == item) {
  return mid;
 } else if (a[mid] < item) {
   low = mid + 1;
 } else {
   high = mid - 1;
 }
 if(a[high] < item) {// invalid size read of 4
  return high + 1;
 }
 }
 return KEY_NOT_FOUND;
}

However, it may cause invalid read size read of 4 at

if(a[high] < item)

Can somone explain(or give an example) why does this line cause invalid read size read of 4? Thanks in advance.

Let's say low == high == 0 the start of the while loop.

So, mid == 0

Then the code does high = mid - 1; So, high is now negative, and a[high] is an illegal access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM