tourism
tourism

Reputation: 155

Why I am getting the segmentation fault in following c program

The following code gets compiled successfully but I am getting the Segmentation fault in the first line of the main function. I am not getting why I am getting this error.

#include <stdio.h>
#include <math.h>
unsigned int prime=2;

void resetprimegenerator()
{
    prime=2;
}

unsigned int getnextprime()
{
    while(1)
    {
        if(isprime(prime))
            return prime;
    }

}

int isprime(unsigned int n)
{
    int i=3,check=1;
    if(n==2)
        return n;
    for(i=3;i<=sqrt(prime);i+=2)
    {
        if(prime%i==0)
        {
            check=0;
            break;
        }
    }
    return check;
}
int main()
{
    int t,n,i=0,j=0;
    int input[500];
    unsigned int answer[500][5000];
    scanf("%d",&t);
    getchar();
    while(t-->0)
    {
        scanf("%d",&input[i]);
        getchar();
        n=input[i];
        j=0;
        resetprimegenerator();
        while(n-->0)
        {
            answer[i][j]=getnextprime();
            j++;
        }
        i++;
    }
    for(i=0;i<t;i++)
    {
        for(j=0;j<input[i];j++)
        {
            if(j==input[i]-1)
                printf("%u",answer[i][j]);
            else
                printf("%u ",answer[i][j]);
        }
    }
    return 0;
}

I am not getting why I am getting the following error.

Upvotes: 2

Views: 102

Answers (2)

2501
2501

Reputation: 25753

You are running out of stack space when you declare

unsigned int answer[500][5000];

Instead, allocate it on the heap; use malloc().

For example you can use a pointer to an array:

int ( *array )[5000] = malloc( sizeof( *array ) * 500 ) ;

array[0][0] = 1234 ;

Where sizeof( *array ) is equal in value as sizeof(int) * 5000

Upvotes: 4

Yu Hao
Yu Hao

Reputation: 122493

unsigned int answer[500][5000];

Assuming unsigned int is 4 bytes, this variable will occupy about 10MB of stack size. That's bigger than the size of a normal stack, what you have is stack overflow.

The solution is to use dynamic allocation, or make it global / static. Choose according to your need.

Upvotes: 7

Related Questions