-3
#include <stdio.h>
int main()
{    
    int array[10];
    array[50] = 5;
    printf("array[50] = %i \n", array[50]);
}

Above code works without a problem when is shouldn't. Why is that? This behaviour could make finding a potential bug in the program quite tricky.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Rafal
  • 15
  • 3

1 Answers1

2

The behaviour of an out of bounds array access such as this is undefined.

Undefined behaviour can manifest itself as the program working as you intended!

This does indeed make programming in C tricky, and the language draws criticism for being unsafe in this respect (cf. FORTRAN which grew up contemporaneously). Such pernicious behaviour can be obviated somewhat by adopting appropriate programming practices that have grown up since C was invented in the 1970s. Bounds checking software has also been invented which will weed out bugs such as this.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483