条件下的分段故障

时间:2012-10-14 17:55:05

标签: arrays segmentation-fault primes

我的程序的目的是找到用户输入指示的素数。我设置了一个数组来存储素数,因为它找到了它们。当p(测试中的整数)递增并且测试重新开始时,仅通过除以数组内的元素来保存处理。它工作到44030年初。我正在使用GCC进行编译。为什么它会给我一个分段错误?

 //Prime Finder
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i=4;
int p=7;
int j=1;
int cap;
printf("\nWhich prime number would you like to see? ");
scanf("%i",&cap);
long *array=malloc(cap);
array[0]=1;
array[1]=2;
array[2]=3;
array[3]=5;
while(i<=cap)
{
if (array[j]>=p/2) // if true then p is prime
{
    j=1;
    array[i]=p;
    p++;
    i++;
}
else if (p%array[j]==0) // if true then p is not prime
{
    p++;
    j=1;
}
else // in this case p is still under test
    j++;
}
printf("\nHere it is! %i\n\n",array[cap]);
return 0;
}

1 个答案:

答案 0 :(得分:0)

您在cap电话中分配cap*sizeof(long)字节而不是malloc()字节。所以你要覆盖内存的其他部分;究竟何时取决于您为上限提供的价值。