递归导致的分段错误 [英] Segmentation fault due to recursion
问题描述
我正在编写一个程序,该程序将取一个 1-10 之间的数字并显示所有可能的数字排列方式.
I'm writing a program that is to take a number between 1-10 and display all possible ways of arranging the numbers.
前输入:3输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
每当我输入 9 或 10 时,程序都会给出分段错误并转储内核.我相信问题是我的递归算法被调用了太多次.有人可以帮助指出我如何限制必要的递归调用量吗?这是我当前的代码:
Whenever I input 9 or 10, the program gives a segmentation fault and dumps the core. I believe the issue is my recursive algorithm is being called too many times. Could someone help point out how I could limit the amount of recursive calls necessary? Here is my current code:
void rearange(int numbers[11], int index, int num, int fact) {
int temp = numbers[index];
numbers[index] = numbers[index-1];
numbers[index-1] = temp;
int i;
for (i = 1; i <= num; ++i) // print the current sequence
{
printf("%d ", numbers[i]);
}
printf("
");
fact--; // decrement how many sequences remain
index--; // decrement our index in the array
if (index == 1) // if we're at the beginning of the array
index = num; // reset index to end of the array
if (fact > 0) // If we have more sequences remaining
rearange(numbers, index, num, fact); // Do it all again! :D
}
int main() {
int num, i; // our number and a counter
printf("Enter a number less than 10: ");
scanf("%d", &num); // get the number from the user
int numbers[11]; // create an array of appropriate size
// fill array
for (i = 1; i <= num; i++) { // fill the array from 1 to num
numbers[i] = i;
}
int fact = 1; // calculate the factorial to determine
for (i = 1; i <= num; ++i) // how many possible sequences
{
fact = fact * i;
}
rearange(numbers, num, num, fact); // begin rearranging by recursion
return 0;
}
推荐答案
9!
(362880) 和 10!
(3628800) 是超出 调用堆栈,当您执行尽可能多的递归调用时.因为必须存储所有局部变量和形式参数.您要么必须增加堆栈大小,要么将递归转换为迭代.
9!
(362880) and 10!
(3628800) are huge numbers that overflow the call stack when you do as many recursive calls. Because all the local variables and formal parameters have to be stored. You either you have to increase the stack size or convert the recursion into iteration.
在 linux 上,你可以这样做:
On linux, you can do:
ulimit -s unlimited
将堆栈大小设置为无限制.默认值通常为 8MB.
to set the stack size to unlimited. The default is usually 8MB.
这篇关于递归导致的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!