0

我正在尝试编写一个简单的程序来计算两个数字的公因数。我在扫描第二个数字时遇到分段错误(核心转储)。我不明白故障在哪里?

#include <stdio.h>
#include <stdlib.h>

int main()
{
long long int first,second,t,k;
long long int i,count=0;
scanf("%lld",&first);
scanf("%lld",&second);
//storing the lowest of two numbers in t  
if(first<second){
    t=first;
}
else{
    t=second;
}
//initialising an array to be used as flags
int com[t];
for(i=0;i<t;i=i+1){
    com[i]=1;
}
for(i=0;i<t;i=i+1){
    if(com[i]==1){
        if(first%(i+1)==0&&second%(i+1)==0){
            count=count+1;
        }
        else{
            for(k=2;k*(i+1)-1<t;k=k+1){
                com[k*(i+1)-1]=0;
            }
        }
    }
}
printf("%lld\n",count);
 return 0;
}
4

1 回答 1

3

我怀疑您的输入是一个非常大的数字(编辑:您在评论中确认了它)。调用堆栈的大小相当有限,声明一个巨大的可变长度数组很容易溢出。

替换int com[t];为以下内容:

int *com = malloc(sizeof *com * t);

当然,完成后不要忘记释放它。

于 2017-04-05T08:12:35.800 回答