0

The following is my code in C

main(){

    int a[1];
    a[0]=10;
    a[1]=12;
    printf("%d\n",a[1]);
    copy_arr(a);
    printf("%d",a[1]);
}

The following is the output

12
12

Shouldn't it give array out of bound or something like this?

Or does the code above depend on the compiler?

I am running the above in a gcc compiler.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Aditya Sharma
  • 389
  • 3
  • 11
  • 3
    `main()` should be `int main(void)`, and you need `#include ` at the top. Where is `copy_arr` defined? – Keith Thompson Jan 17 '15 at 08:49
  • The compiler *should* give you a warning that your array access is out of bounds, and the clang compiler *does* warn you. Not sure why gcc doesn't. – user3386109 Jan 17 '15 at 08:49
  • With *gcc*, be sure to enable warnings with `-Wall -Wextra` compiler flags. – hyde Jan 17 '15 at 08:51
  • Related: http://stackoverflow.com/q/7410296/694576 – alk Jan 17 '15 at 08:52
  • @user3386109 The compiler could figure it out in this particular case. But in most real life scenarios, the indexing is based on some runtime information. – juanchopanza Jan 17 '15 at 09:00

3 Answers3

4

There's no automatic array bounds checking in C. Your code has undefined behaviour (UB). This means it can sometimes seem to "work". But you can't rely on any particular outcome. A program with UB is a broken program.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3

Accessing out-of-bound memory is undefined behaviour. Be it statically allocated or dynamically.

Point to note: C does not have any in-built feature of checking out-of-bound array access. So, you'll not be warned by default [as you might have expected].

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2
int a[1];

This array can just hold a single integer and the valid access is a[0] , a[1] will be array out of bound access which is undefined behvaior.

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • @alk I meant the results are not consistent and it might work sometimes and might not sometimes – Gopi Jan 17 '15 at 08:51