为什么我的递归函数在C中出错?

del*_*ber 0 c recursion

我的计划如下:

#include <stdio.h>

int collatz(int seed, int count) {
    int next = 0;
    if (seed % 2 == 0) {
        next = seed / 2;
    } else {
        next = 3 * seed + 1;
    }
    count++;
    if (next == 1) {
        return count;
    } else {
        return collatz(next, count);
    }
}

int main() {
    int max = 0;
    int index = 0;
    int i;
    for (i=1; i<1000000; i++) {
        int current = collatz(i, 1);
        if (current > max) {
            max = current;
            index = i;
        }
    }
    printf("%i\n", index);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我知道递归通常只会达到一定的深度.但是据我所知,我已经实现了尾递归,应该停止seg故障.如果我将i设置为100,000,程序运行会让我相信基础算法是正确的.然而我得到一百万:

分段错误:11

我究竟做错了什么?

Joh*_*nck 10

如果你使用调试器,你可能会发现你的函数确实不是尾递归的.但为什么不呢?可能是因为您只是忘了在编译期间启用优化.在我的系统上(Mac OS上的GCC),默认构建将崩溃,但使用该-O3选项构建将使其运行(至少比其他时间更长;我不想杀死我的电池测试).