Search code examples
csieve-of-eratosthenes

Runtime error in finding prime numbers


Spoj problem- http://www.spoj.com/problems/PRIME1/
There is a logical error in the code and is not running.
IDE-Codeblocks

int main()
{
    int t,*prime;
    long long int m,n,i,j;
    //t for number of test cases

    scanf("%d",&t);

    for(i=0;i<t;i++)
    {
        scanf("%llu%llu",&m,&n);
        prime=(int*)(malloc((n-m)*sizeof(int)));

        //Initialising all elements as 1 
        for(i=0;i<m;i++)
        {
            prime[i]=1;
        }

        prime[0]=0;
        prime[1]=0;

        //Initialising all the multiples of primes as 0 as in sieve algorithm
        for(i=m;i<n;i++)
        {
            if(prime[i]!=0){
                for(j=2;j*i<=1000000000;j++)
                {
                    prime[j*i]=0;
                }
            }
        }

        for(i=m;i<n;i++)
        {
            printf("%llu\n",i);
        }

        free(prime);
    }
    return 0;
}

Solution

  • scanf("%lld %lld",&m,&n);
    prime=(int*)(malloc((n-m)*sizeof(int)))
    

    You are allocating memory for n-m elements and you are trying to access the mth to n-1 th element which is out of bound access which will lead to undefined behavior hence you are seeing a crash.

    There are similar other access in the same loop so you should take care of this.

    For example:

    The input is 5 and 10 i.e m=5 and n=10 ( Format specifier should be %lld for long long)

    Now the memory allocated is for 5 elements prime[0] to prime[4] .

    In the for loop you have access like i<n In this case you will have access like

    prime[9] which will cause crash because you are accessing some memory which is not allocated by you

    The other access has

    prime[j*i] What if i=3 and j=4

    You are accessing prime[12]