[英]Why does my left shift function give a seg fault unless I use an if statement to terminate?
[英]Why does my recursive function seg fault in C?
我的程序如下:
#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;
}
我了解到递归通常只会达到一定深度。 但是据我所知,我已经实现了尾部递归,这应该可以停止seg错误。 如果将i设置为100,000,程序将运行,这使我相信基础算法是正确的。 但是,一百万我得到:
细分错误:11
我究竟做错了什么?
如果使用调试器,您可能会发现您的函数确实不是尾递归的。 但是为什么不呢? 可能是因为您只是忘记了在编译期间启用优化。 在我的系统(Mac OS上为GCC)上,默认构建会崩溃,但是使用-O3
选项进行构建将使其运行(至少比其他时间更长;我不想终止电池测试)。
如果您使用一百万运行它,我会说您可能只是堆栈空间不足而导致段错误
VS堆栈大小中使用的编译器/操作系统默认情况下为1MB,但可以增加。 我不确定其他编译器/操作系统组合
collatz函数在计算中间导致溢出。 (为此,它的堆栈溢出)。
注意:针对尾部递归的编译器优化可能会或可能不会完成。
使用long long(Int64)。
int collatz(long long seed, int count) {
long long 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.