Question

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?

Was it helpful?

Solution

long int d[500] declares an array with 500 items indexed from 0 to 499

d[500] is outside the bounds of your array.

OTHER TIPS

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.

printf("%ld\n", d[500]); - accessing beyond the array.

d[i] = d[i-1] + d[i-2] + d[i-3]; - accessing beyond the array.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top