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?

3
  • 4
    You are just getting lucky.. it should/could seg fault and it will when you shoot yourself in the foot. Commented Jul 6, 2012 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. Commented Jul 6, 2012 at 13:01
  • 1
    stackoverflow.com/a/6445794/193903 essential reading :) Commented Jul 6, 2012 at 13:12

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

+1 for mentioning the connection c/performance/no bound checking
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.