Home » C programming language

What happens if we use out of bounds index in an array in C language?

Out of bounds array indexing in C programming language: Here, we will learn that what happens if we use out of bound array indexing in C language?
Submitted by IncludeHelp, on May 28, 2018

Let’s understand first, what is index out of bounds?

Let suppose you have an array with 5 elements then the array indexing will be from 0 to 4 i.e. we can access elements from index 0 to 4.

But, if we use index which is greater than 4, it will be called index out of bounds.

If we use an array index that is out of bounds, then the compiler will probably compile and even run. But, there is no guarantee to get the correct result. Result may unpredictable and it will start causing many problems that will be hard to find.

Therefore, you must be careful while using array indexing.

Consider the example:

#include <stdio.h>

int main(void) 
	int arr[5];
	int  i;
	arr[0] = 10;  //valid
	arr[1] = 20;  //valid
	arr[2] = 30;  //valid
	arr[3] = 40;  //valid
	arr[4] = 50;  //valid
	arr[5] = 60;  //invalid (out of bounds index)
	//printing all elements
	for( i=0; i<6; i++ )
		printf("arr[%d]: %d\n",i,arr[i]);

	return 0;


    arr[0]: 10
    arr[1]: 20
    arr[2]: 30
    arr[3]: 40
    arr[4]: 50
    arr[5]: 11035


In the program, array size is 5, so array indexing will be from arr[0] to arr[4]. But, Here I assigned value 60 to arr[5] (arr[5] index is out of bounds array index).

Program compiled and executed successfully, but while printing the value, value of arr[5] is unpredictable/garbage. I assigned 60 in it and the result is 11035 (which can be anything).


Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.