0
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?

CDT
  • 10,165
  • 18
  • 66
  • 97

4 Answers4

4

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

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

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • Oh, this is really embarrassing...It's the first time I come into bus error and didn't even think of checking array boundary... – CDT Jan 28 '13 at 05:33
  • The root cause is the out of bounds access inside the loop because it precedes the access in `printf`. what happens after the first out of bounds access is pretty much pointless. The program ceased to be a valid program when the first UB occured. – Alok Save Jan 28 '13 at 05:37
  • I'm referring to any access to d[500], in the loop or otherwise. – Mitch Wheat Jan 28 '13 at 05:39
2

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

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

sunmoon
  • 1,448
  • 1
  • 15
  • 27
  • ...and so does assignment to `d[i]` in the for loop with `i<=500` – Anton Kovalenko Jan 28 '13 at 05:23
  • @AntonKovalenko: And that is the root cause because it precedes the access in `printf`. Basically the UB happened during the loop and hence what happens after is pretty much pointless. The program ceased to be a valid program when the first UB occured. – Alok Save Jan 28 '13 at 05:30
  • Thanks. I should not have ignored such a beginner mistake. – CDT Jan 28 '13 at 05:39
2
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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Thanks... I should have noticed that... It's the first time I got bus error so I didn't mention to check array boundary... – CDT Jan 28 '13 at 05:37
  • @CDT: I am going to repeat this for the third time here: *The root cause is the out of bounds access inside the loop because it precedes the access in `printf`. what happens after the first out of bounds access is pretty much pointless. The program ceased to be a valid program when the first UB occured.* – Alok Save Jan 28 '13 at 05:41
0

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.

Aatish Sai
  • 1,647
  • 1
  • 26
  • 41