-6

The following code has an array of fixed size 2 that means it should store maximum 3 elements a[0],a[1],a[2] but on giving further values compiler don't show any error message and the values are stored correctly.How?

#include <stdio.h>
int main() {
    int a[2];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 9;
    a[4] = 99;
    printf("%d\n", a[0]);   
    printf("%d\n", a[1]);
    printf("%d\n", a[2]);
    printf("%d\n", a[3]);
    printf("%d\n", a[4]);

    return 0;
}

OUTPUT: -1 2 3 9 99.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Rak
  • 53
  • 1
  • 5
  • Because C doesn't require bounds checking. What you're seeing is undefined behaviour. –  Mar 05 '16 at 20:17
  • Also, `int a[2]` means that it stores **two items** (exactly two, not just at maximum), `a[0]` and `a[1]`. Using `a[2]` is already undefined behaviour, because it lies outside of the array. –  Mar 05 '16 at 20:18
  • See [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). Behind the scenes, your program is doing really bad stuff. That usually, but not always, results in bad output or a crash. – user3386109 Mar 05 '16 at 20:19
  • You can read how this is dangerous [here](http://stackoverflow.com/questions/15646973/how-dangerous-is-it-to-access-an-array-out-of-bounds) – ppsz Mar 05 '16 at 20:20
  • so you mean by declaring an array a[2], i can only use a[0] and a[1]. – Rak Mar 05 '16 at 20:22
  • Yes, that is correct. – user3386109 Mar 05 '16 at 20:23

1 Answers1

0

No, an array of size 2 is not meant to store 3 elements, it can only store 2 elements. C does not prevent you from trying to access arrays beyond their boundaries, but the code then invokes undefined behavior.

The compiler should be smart enough to detect your erroneously accessing a[2], a[3] and a[4]. Maybe you did not give it enough of a warning level or maybe changing the optimization settings can do it. In any case, your code invokes undefined behavior, so anything can happen.

Here is a corrected version:

#include <stdio.h>
int main() {
    int a[5];

    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 9;
    a[4] = 99;
    printf("%d\n", a[0]);    
    printf("%d\n", a[1]);
    printf("%d\n", a[2]);
    printf("%d\n", a[3]);
    printf("%d\n", a[4]);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189