tags:

views:

276

answers:

5

I was told this is a buggy code, but I don't know why, some could explain it to me. why there would not be an array out of bound exception when I compile?

int a[10];
int j;

void main () {
    int i, j = 42;
    for (i = 0; i <=10; i++) a[i] = i;
    printf("%d", j);
}
+25  A: 

You've allocated 10 spaces. You fill 11.

Ignacio Vazquez-Abrams
+7  A: 

Change

int a[10];

to

int a[11];

or

for (i = 0; i <=10; i++) a[i] = i;

to

for (i = 0; i < 10; i++) a[i] = i;

You've created an array with a count of 10 and try to put 11 elements in it. You either need to put only 10 elements in it or create a bigger array.

userx
Technically correct, but does not explain *why* it fails in the first place.
Charlie Salts
You can also autodetect the size of `a`:`for (i = 0; i < sizeof(a)/sizeof(a[0]); i++) a[i] = i;`
dolmen
+2  A: 

Here's one bug:

void main () {

should be

int main (int argc, char** argv) {

Another bug is in your loop. You write past the end of array a, and if your compiler placed j in memory immediately following a (which based on your question I assume it did), then the out-of-bounds array access will actually end up assigning a value to j. Hence, when you write 10 into a[10] (which doesn't exist), you are writing it into the memory where j lives (causing this to act like j = 10). However, this behavior is dependent on how your compiler lays out the variables in memory, so you may very well see different behavior if you compiled the same program on a different platform.

bta
I would say in this case `int main(void)` would be more ideal to convey that this program takes no arguments but it should still return an `int`.
SiegeX
Not necessarily a bug - it could be that he wants main to return nothing and use no arguments.
Michael Dorgan
@Michael Dorgan: +1 the C99 standard explicitly allows main to have any return type you (or, more accurately, the implementation) like.
JeremyP
@Michael Dorgan It doesn't matter what he wants, it matters what the standard mandates. (P.S. an empty parameter list doesn't mean "no arguments") @JeremyP Read more closely; that's only true for freestanding environments.
Cirno de Bergerac
A: 

There should not be an overflow of array, thats correct as you have mentioned in your question. But some compilers will give a PASS with the code whereas others will trigger a warning (or error is elevated).

wrapperm
+1  A: 

filling array crossing the boundary...a[10] is wrong.

chaitanyavarma