0

Even Fibonacci Numbers - Project Euler ,Getting some error (Segmentation Fault(core dumped)) Here is the code, Can anyone help to find the mistake ?

int main()
{
    int arr[4000000];
    int i,sum=0;
    arr[0]=1;
    arr[1]=2;
    for(i=2; i<4000000; i++)
    {
        arr[i] = arr[i-1] + arr[i-2];
    }
    for(j=0; j<4000000; j++)
    {
        if(arr[j]%2==0)
        {
            sum = sum + arr[j];
        }
    }
    return 0;
}
mschuurmans
  • 1,000
  • 1
  • 10
  • 24
TRK
  • 1
  • Does it help if you change `int arr[4000000];` to `int *arr=malloc(4000000);`? – Blaze Oct 18 '18 at 10:39
  • I wonder at which element Fibonacci numbers stop fitting in a regular int. – user6144226 Oct 18 '18 at 10:42
  • It shouldn't compile, you've forgot to declare `j` – Cid Oct 18 '18 at 10:43
  • @Cid yes, but that would not give segmentation fault core dumped error. – suvojit_007 Oct 18 '18 at 10:45
  • I wonder if this is a case of integer overflow. the max value of int in C is 32,767 and as we are trying to go to 4000000 it might go try to allocate negative indexes – Dinomaster Oct 18 '18 at 10:47
  • @user6144226 seems like someone else tried that: https://stackoverflow.com/questions/33733511/c-print-first-million-fibonacci-numbers looks like it's not even getting to 100. – Blaze Oct 18 '18 at 10:47
  • 1
    @suvojit_007 there can't be seg fault if code doesn't compile. – Cid Oct 18 '18 at 10:50
  • @Cid did "Explicit type is missing (int assumed)" stop being a thing? – user6144226 Oct 18 '18 at 10:53
  • @Dinomaster the actual size of int isn't defined - should be at least that. You can expect it to be "4 bytes" on any modern PC – user6144226 Oct 18 '18 at 10:56
  • @user6144226 true but by definition of a segfault(https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) we must assume we are trying to writing somewhere we are not allowed to. So either the program can't alloc the needed memory or the write to array is doing something wonkey. – Dinomaster Oct 18 '18 at 11:05

1 Answers1

1

In a nutshell, I would say you are getting Segmentation fault core dumped error because your program exceeded the stack memory. (Stack overflow)

A stack overflow is when you've used up more memory for the stack than your program was supposed to use.

Your program is asking for about 16MB of space in the stack memory which is way bigger than default stack memory space.

How does a "stack overflow" occur and how do you prevent it?

suvojit_007
  • 1,649
  • 2
  • 12
  • 21
  • Even though OP will not be able to achieve his requirement because of integer overflow(`sum` and `arr` will ultimately overflow ). – kiran Biradar Oct 18 '18 at 11:07