Accessing array out of bounds in C/C++

CC++Server Side Programming

In a language such as Java, an exception such as java.lang.ArrayIndexOutOfBoundsException may occur if an array is accessed out of bounds. But there is no such functionality in C and undefined behaviour may occur if an array is accessed out of bounds.

A program that demonstrates this in C is given as follows.

Example

 Live Demo

#include <stdio.h>
int main() {
   int arr[] = {1,2,3,4,5};
   printf("The elements of array : ");
   for(int i = 0; i<6; i++)
   printf(" %d",arr[i]);
   return 0;
}

Output

The output of the above program is as follows.

The elements of array : 1 2 3 4 5 32765

Now let us understand the above program.

The array arr has assigned values only till subscript 4. So when the array elements are printed, arr[5] results in a garbage value. The code snippet that shows this is as follows.

int arr[] = {1,2,3,4,5};
printf("The elements of array : ");
for(int i = 0; i<6; i++)
printf(" %d",arr[i]);
raja
Updated on 26-Jun-2020 14:08:50

Advertisements