1

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.

1
  • Congratulations on using valgrind to spot such problems. Commented Jul 23, 2013 at 17:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.