递归引起的分段错误

Sla*_*ter 1 c recursion coredump sequence segmentation-fault

我正在写一个程序,它取一个1-10之间的数字,并显示所有可能的方法来安排数字.

防爆输入:3输出:

   1 2 3
   1 3 2
   2 1 3
   2 3 1
   3 1 2
   3 2 1
Run Code Online (Sandbox Code Playgroud)

每当我输入9或10时,程序会产生分段错误并转储核心.我相信问题是我的递归算法被调用了太多次.有人可以帮助指出我如何限制必要的递归调用量?这是我目前的代码:

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("\n");

  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;
}
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

9!(362880)和10!(3628800)是在执行尽可能多的递归调用时溢出调用堆栈的巨大数字.因为必须存储所有局部变量和形式参数.您要么必须增加堆栈大小,要么将递归转换为迭代.

在linux上,你可以这样做:

ulimit -s unlimited
Run Code Online (Sandbox Code Playgroud)

将堆栈大小设置为无限制.默认值通常为8MB.