0

While playing around with arrays, and experimented with this program:

#include <stdio.h>

int main ( void )
{
  int a[] = {};
  printf ( "%d\n", sizeof(a) );
  printf ( "%d\n", a[0] );
  printf ( "%d\n", a[1] );
  printf ( "%d\n", a[10] );
  printf ( "%d\n", a[100] );
}

And somehow, it compiled successfully without errors got this result:

0
-1216614400
134513834
-1080435356
-1080430834

How come I am able to access an empty array at any index that should have no size?

vxs8122
  • 834
  • 2
  • 10
  • 22
  • 1
    See [Is accessing a global array outside its bound undefined behavior?](http://stackoverflow.com/q/26426910/1708801) – Shafik Yaghmour Mar 13 '15 at 13:44
  • "*at any index that should have no size*", what do you mean? – Iharob Al Asimi Mar 13 '15 at 13:52
  • Which compiler? I am guessing `clang` but perhaps `gcc`? – Shafik Yaghmour Mar 13 '15 at 13:55
  • Something to meditate on: `a[i]` is equivalent to `*(a + i)` - so much so that you can write `10[a]` instead of `a[10]` (not that you should, of course). So you're just accessing locations in memory, not calling methods on some fancy data structure implementation… – Arkku Mar 13 '15 at 13:59

1 Answers1

0

In your code

printf ( "%d\n", a[0] );
printf ( "%d\n", a[1] );
printf ( "%d\n", a[10] );
printf ( "%d\n", a[100] );

produces undefined behaviour by accessing out-of-bound memory.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261