SPOJ#2分段故障(SIGSEGV)

时间:2013-12-29 18:00:24

标签: c sieve-of-eratosthenes

我试过了SPOJ#2。我只是无法确定哪条线是故障的问题。 试图通过'Eratosthenes筛选'来解决这个问题

#include<stdio.h>
int main()
{

    unsigned long long int i,j,LIMIT,NUM1; 

// NUM1 and LIMIT are the starting numbers of the range
//like for prime numbers between 31-100 NUM1 = 31 and LIMIT = 100

    int *primes;
    int z = 1,t;

    scanf("%d",&t);
    while(t--){

    scanf("%lld",&NUM1);
    if(NUM1==1)
        ++NUM1;
    scanf("%lld",&LIMIT);

    primes = malloc(sizeof(int)*(LIMIT));

    for(i=2; i<=LIMIT;i++)      //initialise every element by 1
        primes[i] = 1;

    for (i=2;i<LIMIT;i++)
    {
        if (primes[i])
    for(j=i;j*i<=LIMIT;j++)
        primes[i*j]=0;          // make 0 all elements that are factor of 'j'
    }

    for (i=NUM1;i<=LIMIT;i++)
    {

        if(primes[i])
            printf("%d\n",i);   
// prime[i] will be one for leftover elements which are prime
    }
}
    return 0;
}

1 个答案:

答案 0 :(得分:3)

primes = malloc(sizeof(int)*(LIMIT));

for(i=2; i<=LIMIT;i++)      //initialise every element by 1
    primes[i] = 1;

错了。您分配LIMIT整数,其索引从0到LIMIT-1。你不能分配到素数[LIMIT],这是你的最后一个循环。替换为

primes = malloc(sizeof(int)*(LIMIT+1));

if (primes==NULL) {
    fprintf(stderr, "Can't allocate that much space\n";
    exit(1);
}
for(i=2; i<=LIMIT;i++)      //initialise every element by 1
    primes[i] = 1;