【发布时间】:2016-02-03 20:00:57
【问题描述】:
当我运行以下使用gcc 编译的代码(打开的唯一选项是-std=c99)并运行可执行文件时,我得到一个分段错误(msg 核心转储)。
这是为什么呢?
#include <stdio.h>
int count_factors(int n, int i) {
int m = n;
if (m == i) {
return 1;
} else if (m % i == 0) {
while (m % i == 0) m = m / i;
return 1 + count_factors(m, i);
} else {
return count_factors(m, i+1);
}
}
int main() {
int streak_size = 4;
int streak = 0;
int solution = 0;
int n = 2;
while (solution == 0) {
n += 1;
int c = count_factors(n, 2);
if (c == streak_size) {
streak += 1;
} else {
streak = 0;
}
if (streak == streak_size) solution = n;
}
printf("%i", solution);
return 0;
}
【问题讨论】:
-
因为在
count_factors中你永远无法摆脱递归。把printf("%d %d\n", n, i);放在count_factors开头就明白了。 -
哦,讽刺的是,在一个名为“StackOverflow”的网站上。
-
编译时应始终启用警告,例如
-Wall。请注意,这是一般建议,可能无助于解决您的特定问题。 -
当然,通过琐碎的调试无法检测到失控的递归...... :((
-
嗨,我想检测像这样的无限递归错误属于停止问题,所以编译器不可能检测到它?还是我夸大了?
标签: c recursion segmentation-fault