使用Eratosthenes Sieve程序进行分段故障

时间:2014-03-08 05:40:22

标签: c primes sieve-of-eratosthenes sieve

我正在尝试实施筛选算法,它会询问连续数字列表的大小并打印出该列表中的素数,但是我遇到了一个seg错误:11错误。

这是我的代码:

#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;
}

2 个答案:

答案 0 :(得分:1)

char n[LIMIT];

LIMIT的值为1000000,这是一个非常大的数组(一百万字节)。这会导致stack overflow。您需要为它动态分配内存:

char *n = malloc(LIMIT);

答案 1 :(得分:0)

代码以奇怪的方式使用n。建议只扫描整数n并使用n结束循环而不是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;
}