-2

In the following code, I've assigned values to an array elements which are out of the array boundaries, In Linux environment in the CLI the code give me the error message: array index 5 is past the end of the array which contains 5 elements.

But while debugging on IDE codeblocks -compiler cannot find this bug- so is there any explanation?

#include <stdio.h> 
int main ()
{
   int array[5],i;
   for (i=0; i<5; i++) {
      array[i] = i+1; 
   }
   array[5] = 666;

   for (i=0; i<5; i++) {
      printf("array[%d]=%d\n", i, array[i]);
   } 
   printf("array[5]=%d\n", array[5]);
   return 0;
}
Ziezi
  • 6,375
  • 3
  • 39
  • 49
Astro
  • 43
  • 1
  • 3

2 Answers2

0

Codeblocks, like most IDEs, does not contain a compiler and won't generate warnings like this by itself. Instead it calls a command-line compiler like gcc, and displays to you the errors and warnings the compiler returns.

You should check what compiler is called, with what compiler options, in Codeblocks/project settings.

gcc should generate an "array subscript is above array bounds" warning for your code, but only with the -Wall and -O2 options (or equivalent).

Optimization (-O2) is often not enabled for debugging, which could be an explanation why you don't get the warning while debugging.

dpi
  • 1,919
  • 17
  • 17
0

When you access an array index, C and C++ don't do bound checking. The values you get when you read are just what happens to exist on the stack at this particular place. They are completely undefined.

The difference between the two compilers is possibly due to the fact that one of those is a newer version including some array bound checking.

Ziezi
  • 6,375
  • 3
  • 39
  • 49