【问题标题】:C runtime error during recursive function call递归函数调用期间的 C 运行时错误
【发布时间】:2018-04-17 17:04:25
【问题描述】:

所以我有一个程序来查找整数 N 可以表示为“n”个整数之和的方式总数。 例如,10 可以表示为 2,3 和 5 的组合如下-

10 = 5 + 5

10 = 5 + 3 + 2

10 = 3 + 3 + 2 + 2

10 = 2 + 2 + 2 + 2 + 2

#include<stdio.h>
#include<stdlib.h>
int ways(int,int*,int);


int main()    {
    int n,num; //n is number of possible integers 
    scanf("%d",&n);
    int*curr=(int*)malloc(n*sizeof(int));     //dynamically allocated array that stores all "n" integers in array form
    for(int i=0;i<n;i++)    {
        scanf("%d",curr+i); 
    }
    int t,N; //t is number of test cases
    scanf("%d",&t);
    while(t--)    {
        scanf("%d",&N);     //for each test case, scans the number N that needs to be expressed as a sum of combinations those "n" integers
        num=ways(N,curr,n);
        printf("%d\n",num);
    }
    return 0;
}

int ways(int N,int*p,int size) {
    int flag=1;
    for(int i=0;i<size;i++) {
        if(N/(*(p+i))!=0)  {
            flag=0;
            break;
        }
//Above loop says that if number N is less than all of the "n" integers, it 
cannot be expressed as their sum. Hence, 0 will be returned if flag is 1
    }
    if(flag==1)
        return 0;
    if(N==0)
        return 1;
    int num=0,temp;
    for(int i=0;i<size;i++) {
        temp=*(p+i);
        num=num+ways(N-temp,p,size);  //GETTING RUNTIME ERROR AT THIS LINE
    }   
    return num;
}

即使递归深度非常小,程序在递归函数调用时也会出现 SIGSEGV 错误

【问题讨论】:

  • 最好提供导致崩溃的输入...有很多scanf,我们无法猜测所有...
  • 一旦我们到达特定的行,所有输入都会崩溃。
  • 你对我的口味有太多的猜测。您想至少解释所有要输入的值吗?年龄?重量? “n”个?
  • 不要写*(p+i)。只需改用p[i]。否则你只会让阅读变得痛苦。

标签: c recursion segmentation-fault runtime-error


【解决方案1】:

ways 的第一个i 循环中,您似乎正在寻找 数组 p 小于 N (尽管除法是一个可怕的 低效的测试方式)。找到一个,你做其他事情,然后 使用另一个i 循环,丢失你在第一个找到的i 的值 一,递归调用ways

现在,请注意您在第二个循环中不进行任何测试。完全是 可以从N 中减去大于N 的东西,得到一个 否定的结果,并通过。这会导致无限递归,不是吗?

【讨论】:

  • 我想就是这样。它需要检查N - temp
  • 谢谢,运行时错误已通过将 if(flag==1) 替换为 if(flag==1||N
【解决方案2】:

SIGSEGV 错误是分段错误错误,这意味着您正在尝试访问程序无法访问的内存位置。 这是最常见的,因为取消引用空指针或在您的 for 循环中遍历。尝试检查代码的逻辑。

我认为当你输入 *(p + 1) 时,你会在某个时候越界。尝试使用断点调试或在 for 循环中输出 *(p+1) 的值。

【讨论】:

  • 更有可能是堆栈溢出。
  • 错误不是由于指针取消引用,因为即使在大数组的情况下我也会遇到同样的错误
猜你喜欢
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 2014-11-16
  • 2015-02-24
相关资源
最近更新 更多