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
tthat is the thesuccessorofk, if one exists, else returnKEY_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.
valgrindto spot such problems.