I have implemented the below version of the Sieve of Eratosthenes that allocates memory on the heap to store the array representing prime numbers.
void sieve(int *primes, int n) {
for (int i = 0; i < n - 1; i++) {
primes[i] = 1;
}
for (int p = 2; p <= n; p++) {
if (primes[p - 2] == 1) {
for (int i = 2*p - 2; i < n; i += p) {
primes[i] = 0;
}
}
}
}
void print_sieves(int n) {
if (n < 3) return;
int *primes = (int*) malloc((n - 1) * sizeof(int));
sieve(primes, n);
int print_counter = 0;
for (int i = 0; i < n - 1; i++) {
if (primes[i] == 1) {
printf("%10d ", i + 2);
print_counter++;
if (print_counter % COLUMNS == 0)
printf("\n");
}
}
free(primes);
printf("\n");
}
For most arguments passed into print_sieves
the program works as expected, however, when passing 15
into print_sieves
I end up with the following error:
a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
For a slightly different version of this program, in which I instead allocate memory on the stack to store the array representing prime numbers, I run into a different error. Namely, when trying to find too large primes, for example when calling print_sieves
with the argument 10000000
, I encounter the error Segmentation fault (core dumped)
. The implementations of sieve
are identical for both versions of the program, but print_sieves
have slight differences. Below is the code for my print_sieves
function that allocates memory on the stack:
void print_sieves(int n) {
if (n < 3) return;
int primes[n - 1];
sieve(primes, n);
int print_counter = 0;
for (int i = 0; i < n - 1; i++) {
if (primes[i] == 1) {
printf("%10d ", i + 2);
print_counter++;
if (print_counter % COLUMNS == 0)
printf("\n");
}
}
printf("\n");
}
My guess is that I do not manage the memory properly, but I do not know where I am going wrong. What could be causing these errors and how can they be resolved?