为什么我在以下 c 程序中遇到分段错误 [英] Why I am getting the segmentation fault in following c program
本文介绍了为什么我在以下 c 程序中遇到分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码编译成功,但 main
函数的第一行出现分段错误.我不明白为什么会收到此错误.
The following code gets compiled successfully but I am getting the Segmentation fault in the first line of the main
function. I am not getting why I am getting this error.
#include <stdio.h>
#include <math.h>
unsigned int prime=2;
void resetprimegenerator()
{
prime=2;
}
unsigned int getnextprime()
{
while(1)
{
if(isprime(prime))
return prime;
}
}
int isprime(unsigned int n)
{
int i=3,check=1;
if(n==2)
return n;
for(i=3;i<=sqrt(prime);i+=2)
{
if(prime%i==0)
{
check=0;
break;
}
}
return check;
}
int main()
{
int t,n,i=0,j=0;
int input[500];
unsigned int answer[500][5000];
scanf("%d",&t);
getchar();
while(t-->0)
{
scanf("%d",&input[i]);
getchar();
n=input[i];
j=0;
resetprimegenerator();
while(n-->0)
{
answer[i][j]=getnextprime();
j++;
}
i++;
}
for(i=0;i<t;i++)
{
for(j=0;j<input[i];j++)
{
if(j==input[i]-1)
printf("%u",answer[i][j]);
else
printf("%u ",answer[i][j]);
}
}
return 0;
}
我不明白为什么会出现以下错误.
I am not getting why I am getting the following error.
推荐答案
unsigned int answer[500][5000];
假设 unsigned int
是 4 个字节,这个变量将占用大约 10MB 的堆栈大小.这比普通堆栈的大小要大,你所拥有的是 堆栈溢出.
Assuming unsigned int
is 4 bytes, this variable will occupy about 10MB of stack size. That's bigger than the size of a normal stack, what you have is stack overflow.
解决方案是使用动态分配,或者使其成为全局/静态.根据需要选择.
The solution is to use dynamic allocation, or make it global / static. Choose according to your need.
这篇关于为什么我在以下 c 程序中遇到分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文