0

I'm trying to implement the sieve algorithm where it'll ask for the size of a list of consecutive numbers and print out the prime numbers in that list, but I'm getting a seg fault: 11 error.

This is my code:

#include <stdio.h>
#include <stdlib.h>

#define LIMIT 1000000 /*size of integers array*/

int main(void){
    char n[LIMIT];

    //Reads the size of integer array
    printf("Size of array:\n");
    if((fgets(n, LIMIT, stdin)) == NULL) {
        fprintf(stderr, "Could not read from stdin\n");
        exit(1);
    }

    unsigned long long int i,j;
    int *primes;
    int z = 1;

    primes = malloc(sizeof(n));

    for (i = 2; i < sizeof(n); i++){
    primes[i] = 1; //setting every number in list to 1
    }

    for (i = 2; i < sizeof(n); i++){
        if (primes[i]){
            for (j = i; (i*j) < sizeof(n); j++){
                primes[i * j] = 0; //remove multiples
            }
        } 
    }

    for (i = 2; i < sizeof(n); i++){
        if (primes[i]){
            printf("%dth prime = %llu\n",z++,i);
        }
    }

    free(primes);

    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user3291818
  • 203
  • 1
  • 3
  • 11

2 Answers2

1
char n[LIMIT];

With the value of LIMIT being 1000000, that's a really big array (one million bytes). It would cause stack overflow. You need to dynamically allocate memory for it:

char *n = malloc(LIMIT);
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

Code is using n in a curious fashion. Suggest simply scanning the the integer n and using n to end the loops rather than sizeof(n).

#include <stdio.h>
#include <stdlib.h>

int main(void){
    unsigned long n;

    //Reads the size of integer array
    buffer[30];
    printf("Size of array:\n");
    if((fgets(buffer, sizeof buffer, stdin)) == NULL) {
        fprintf(stderr, "Could not read from stdin\n");
        exit(1);
    }
    if (sscanf(buffer,"%lu", %n) != 1) {
        fprintf(stderr, "Unable to covert to a number\n");
        exit(1);
    }

    unsigned long i,j;
    int *primes;
    // int z = 1;

    primes = malloc(n * sizeof *primes);

    for (i = 2; i < n; i++){
      primes[i] = 1; //setting every number in list to 1
    }

    for (i = 2; i < n; i++){
        if (primes[i]) {
            for (j = i; (i*j) < n; j++){
                primes[i * j] = 0; //remove multiples
            }
        } 
    }

    for (i = 2; i < n; i++){
        if (primes[i]){
            printf("%dth prime = %llu\n",z++,i);
        }
    }

    free(primes);
    return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256