Accessing array out of bounds in C/C++


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]);

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements