-3

I wrote a C codes :

#include <stdio.h>
int main()
{
 int i;
 int a[4];
  for( i =0;i<5;i++)
 {
  a[i]=i;
  printf("a[%d]:%d ",i,a[i]);

  }
 return 0;
 }

I used gcc to compile it and succeed to run,the result is :

a[0]:0 a[1]:1 a[2]:2 a[3]:3 a[4]:4

But you can see array a has size of 4,from 0 to 3,i haven't create extra memory to refer to a[4],and unexpectedly it run and seem no errors.In Java,i find if arrays' index out of bounds,it'll throws exception.I just don't know why in C language it just run like right.

shonminh
  • 158
  • 1
  • 2
  • 13
  • 3
    See [Is accessing a global array outside its bound undefined behavior?](http://stackoverflow.com/q/26426910/1708801) the specifics are slightly different but the answers cover all the same ground an answer to this question would. – Shafik Yaghmour Sep 11 '15 at 11:42
  • 3
    Because C has no bounds checking on arrays. When writing to `a[4]` you're just writing somewhere in memory. If you're lucky, you will get a `Segfault`, which will tell you that something is wrong in memory. in most cases, you're just corrupting whatever data was there (and it can have effects way later in your application ... and then "Happy debugging"). – NiBZ Sep 11 '15 at 11:44
  • 1
    @ShafikYaghmour `a[4]` is not global in this case! – CinCout Sep 11 '15 at 11:44
  • @HappyCoder yes, that is why I said *the specifics are slightly different* but the answers are very complete and a complete answer to this will cover almost all the same ground. – Shafik Yaghmour Sep 11 '15 at 11:46
  • Think abut the meaning of **undefined** as in _undefined behaviour_. (This is what you are invoking). – too honest for this site Sep 11 '15 at 12:26
  • @Olaf yes,I know what is undefined,I just have invoked an undefined index which is out of bounds,but I think what I have invoked may be something have defined in stack if index refer to the position in stack. – shonminh Sep 11 '15 at 14:15
  • No, the index is not undefined. UB is invoked once you **dereference** an out-of bounds pointer. **think again!** C does not even have a concept of a stack. – too honest for this site Sep 11 '15 at 14:18
  • @Olaf Thanks to correct. Personal speaking,I have misunderstood segment as stack. – shonminh Sep 11 '15 at 14:58

1 Answers1

1

C doesn't check array boundaries. Segmentation fault will only happen when you read or write to memory your program don't have access to. Simply going past array boundaries won't make your program crash.

But accessing index out of bounds invokes undefined behaviour .

ameyCU
  • 16,489
  • 2
  • 26
  • 41