2

Possible Duplicate:
Array index out of bound in C
Can a local variable's memory be accessed outside its scope?
C no out of bounds error

I am trying out this code snippet,

#include <stdio.h>

main(){
int a[2],i;
a[5] = 12;
for(i=0;i<10;i++){
    printf("%d\n", a[i]);
}
return 0;
}

It gives me output :

1053988144
32767
0
3
0
12
-1267323827
32716
0
0

Why a[5] is accessible ? Shouldn't it through RunTime Error?

Community
  • 1
  • 1
Aashish P
  • 1,894
  • 5
  • 22
  • 36
  • 4
    You are just getting lucky.. it should/could seg fault and it will when you shoot yourself in the foot. –  Jul 06 '12 at 13:00
  • 1
    It *may* seg fault - it *may* also result in almost any other outcome, including nothing at all or even correct operation, since this is Undefined Behaviour. – Paul R Jul 06 '12 at 13:01
  • 1
    http://stackoverflow.com/a/6445794/193903 essential reading :) – unkulunkulu Jul 06 '12 at 13:12

3 Answers3

5

C doesn't have bounds-checking on array access, so no it shouldn't. There is nothing in the language stopping you from attempting to read every (virtual) address you can imagine, although often the operating system and/or computer itself will protest, which might generate some kind of exception. Note that just because you "can" (it compiles and run, seemingly without any ill effects), that doesn't mean the program is valid or that it "works". The results of invalid memory accesses are undefined behavior.

unwind
  • 391,730
  • 64
  • 469
  • 606
4

int a[2]; means "allocate memory that is 2 * sizeof(int)"

a[5] is syntactic sugar for *(a + 5), which point to an area of memory a + (5 * sizeof(int)). So 3 * sizeof(int) past the end of your array. Where is that? Who knows?

Some languages do bound checking, and I have heard of some C compilers that can do it as well, but most do not. Why not do bound checking? Performance. And performance is a major reason for using C in the first place. But that's OK, because C programmers are good programmers and never go beyond the bounds of an array. (hopefully)

cdarke
  • 42,728
  • 8
  • 80
  • 84
1

No control is performed on index bounds. This is simply the way C works.

mouviciel
  • 66,855
  • 13
  • 106
  • 140