简体   繁体   中英

How do the C compiler deal with the local var in stack during recursion?

I write a simple binary search program and meet a problem, see my three confusions below:

  • If I choose icc -g main.c or icc -O0 main.c the code return wrong answer, but if I use icc -O2 main.c I can have the correct answer.

  • When the code mid = (beg + end) / 2; be defined before the if(beg <= end) { the answer is right no matter what flag I use to compile it.

  • I think the problem is the local var mid in the stack during the recursion.

Help me, thank you!

#include <stdio.h>
#define MAX 6
int a[MAX] = {1,2,3,4,5,6};
int improved_binary_search(int key, int beg, int end) {
    int mid, temp;
    //mid = (beg + end) / 2;
    if(beg <= end) {
             mid = (beg + end ) /2;
             if(a[mid] == key)
                     return mid;
             if(a[mid] < key)
                     return improved_binary_search(key, mid + 1, end);
              if(a[mid] > key)
                      return improved_binary_search(key, beg, mid - 1);
              //printf("test is %d\n", mid);
      }
      if(mid == 0)
              return 0;
      if(mid == MAX - 1)
              return MAX - 1;
      if(a[mid] < key)
              return a[mid+1] - key < key - a[mid] ? mid+1 : mid;
      if(a[mid] > key)
              return a[mid] - key < key - a[mid-1] ? mid : mid-1;
      return -1;
  }

int main(void)
{
     printf("%d\n", improved_binary_search(100, 0, MAX - 1));
     return 0;
}

You just declared mid but did not initialize it, it might happen that if the first if condition( if(beg <= end) )is not hit then the value of mid is Indeterminate .

That would result in Undefined Behavior . The behavior you see is because of this UB and not because of compiler configurations.

You should always initialize your variables to meaningful values.

One problem is that you don't initialize mid unless beg <= end . The (potentially uninitialized) variable is then used in the second half of improved_binary_search() . This is undefined behaviour.

To fix, make sure to always initialize mid .

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