Okay, so this function I created uses the Sieve of Eratosthenes algorithm to compute all the primes <= n. This function stores the prime numbers and the count of primes in the parameters.
When the function exits, primes should be pointing to a chunk of dynamically allocated memory that holds all the primes <= num. *count will have the count of primes.
Here is my function getPrimes:
void getPrimes(int usernum, int* count, int** array){
(*count) = (usernum - 1);
int sieve[usernum-1], primenums = 0, index, fillnum, multiple;
//Fills the array with the numbers up to the user's ending number, usernum.
for(index = 0, fillnum = 2; fillnum <= usernum; index++, fillnum++){
sieve[index] = fillnum;
}
/*Starts crossing out non prime numbers starting with 2 because 1 is not a prime. It then deletes all of those multiples and
moves on to the next number that isnt crossed out, which is a prime. */
for (; primenums < sqrt(usernum); primenums++){ //Walks through the array.
if (sieve[primenums] != 0){ //Check's if that number is 0 which means it's crossed out
for (multiple = (sieve[primenums]); multiple < usernum; multiple += sieve[primenums]){ //If it is not crossed out it starts deleting its multiples.
//Crossing multiples out and decrements count to move to next number
sieve[multiple + primenums] = 0;
--(*count);
}
}
}
int k;
for (k = 0; k < usernum; k++)
if (sieve[k] != 0){
printf(" %d", sieve[k]);
}
printf(" ");
array = malloc(sizeof(int) * (usernum + 1));
assert(array);
(*array) = sieve;
}
My function here compiles perfectly, however I noticed I have a segmentation fault when I try larger numbers from like 101 on. Does anyone see where my code is producing a segmentation fault?