Reputation: 10661
long int d[500], i;
d[1] = 1;
d[2] = 2;
d[3] = 4;
for(i = 4; i<=500; i++)
d[i] = d[i-1] + d[i-2] + d[i-3];
int n = 500;
printf("%ld\n", d[500]);
The compiler is gcc. Bus error occurred at compiling. What caused this to happen?
Upvotes: 0
Views: 497
Reputation: 1687
long int d[500]
gives you the memory for 500
long digit integers and are assigned for d[0]
to d[499]
but you are calling d[500]
whose value is not defined.
Upvotes: 0
Reputation: 1498
printf("%ld\n", d[500]);
- accessing beyond the array.
d[i] = d[i-1] + d[i-2] + d[i-3];
- accessing beyond the array.
Upvotes: 2
Reputation: 300739
long int d[500]
declares an array with 500 items indexed from 0
to 499
d[500]
is outside the bounds of your array.
Upvotes: 4
Reputation: 206616
long int d[500];
....
for(i = 4; i<=500; i++)
^^^^^^
You wrote passed the bounds of allocated memory resulting in Undefined behavior.
You are supposed to access array elements only from index 0
to 499
because that is what you allocated.
Upvotes: 2