[英]Segmentation fault in finding factorial
為什么這個程序會出現分段錯誤 (SIGSEGV)。
我試圖找到像 100、200 這樣的大數字的階乘,但我不知道為什么在某些情況下它會顯示分段錯誤。 幫我。
約束:
- 1 ≤ T ≤ 100000
- 1 ≤ N ≤ 100000
#include<stdio.h>
int main()
{
long long int t,mod=1589540031;
long long int a[5000];
long long int n,i,j,temp,k,x;
scanf("%lld",&t);
while(t--)
{
scanf("%lld",&n);
a[0]=1;
k=1;
temp = 0;
for(i=1;i<=n;i++)
{
for(j=0;j<k;j++)
{
x = a[j]*i+temp;
a[j]=x%10;
temp = x/10;
}
while(temp>0)
{
a[k]=temp%10;
temp = temp/10;
k++;
}
}
for(i=k-1;i>=0;i--)
printf("%lld",a[i]%mod);
printf("\n");
}
return 0;
}
a
數組可以包含 5000 個元素,但您不檢查k
和j
是否大於 5000。
一旦您嘗試訪問索引 > 5000 a
數組元素,您就會得到未定義的行為。
for(j=0;j<k;j++)
{
x = a[j]*i+temp; // <<<<< j could be > 5000
a[j]=x%10;
temp = x/10;
}
while(temp>0)
{
a[k]=temp%10; // <<<<< k could be > 5000
temp = temp/10;
k++;
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.