The purpose of my program is to find the prime indicated by user input. I set up an array to store primes as it finds them. As p (the integer under test) increments and the tests restart, processing is saved by only dividing by the elements within the array. It works great up until the 44030th prime. I’m using GCC to compile. Why’s it giving me a segmentatio fault?
//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;
}
You are allocating
capbytes rather thancap*sizeof(long)bytes in yourmalloc()call. So you are overwriting other parts of memory; exactly when depends on what value you provide to cap.