如何判断一段代码为什么会产生死循环?

How to determine why a piece of code produces an infinite loop?

这是我的二进制搜索功能。我似乎找不到错误,但每次我尝试 运行 代码时,它都会给我一个分段错误 11。我觉得我的错误与我最后的 else if 语句有关。

void binary(struct list *A[], char search[15], int start, int 
end) {

    if(start <= end) {

        int middle = (start + end)/2;

        if(strcmp(search, A[middle]->name) == 0){

            printf("found");
            exit(0);

        } else if (strcmp(search, A[middle]->name) > 0){

            int start = middle + 1;
            int end = end;
            binary(A, search, start, end);

        } else if (strcmp(search, A[middle]->name) < 0){

            int start = start;
            int end = middle - 1;
            binary(A, search, start, end);

        } else if (start == (end - 1)) {

            printf("%s was not found in the list", search);
            exit(0);

       }

    }

}

这些陈述

int end = end;
int start = start;

没有意义,因为变量是在具有不确定值的情况下自行初始化的。

不需要声明局部变量end和start。使用参数。

这条语句

    } else if (start == (end - 1)) {

        printf("%s was not found in the list", search);
        exit(0);

   }

也没有意义,因为最初变量startend满足包围if语句

的条件
if(start <= end) {

最后,使用标准函数 exit 而不是 return 语句是没有意义的..

首先,正如其他人已经指出的那样,int end = end 之类的作业是自找麻烦。做一个简单的测试并在函数的开头打印 startend 值,以查看程序运行时会发生什么...

接下来,这里就不用递归了!缩小搜索区域可以在一个简单的循环中轻松完成:

void binary(struct list *A[], char search[15], int start, int end) {
    while(start <= end) {
        int middle = start + (end - start)/2;

        int cmpresult = strcmp(search, A[middle]->name);
        if (cmpresult > 0) {
            start = middle + 1;
        } else if (cmpresult < 0) {
            end = middle - 1;
        } else {             // cmpresult == 0
            printf("found at %d", middle);
            return;
        }
    }

    printf("%s was not found in the list", search);
}

最后,请注意middle的计算——添加(start + end)是一个常见的步骤,但是如果数组太长可能会导致错误;具体来说,如果数组长度超过 int type.

可表示的最大值的一半