Thursday, July 2, 2015

What happens if you try to access or assign array's member out of array's length?

Consider below example for better understanding:


If you have array let say : test[3] = [1,2,3]
so here the length of array is 3 i.e.(test[0],test[1],test[2])
and if you try to access member of test let say test[3] then what will be the output you will be getting  have you ever wonder it?

I have tried this with couple of languages and output was like below:

In C:
if you try to access the element test[3] then it will give me some garbage value but no error will appear

In python :
If I try to access the element test[3] then it will throw error "IndexError: list index out of range"

In Java :
If I try to access the element test[3] then it will throw "error java.lang.ArrayIndexOutOfBoundsException"

In JavaScript:
If I try to access the element test[3] then it will give me output as "undefined"

So as you can see above results indicates that there is something strange happening when we access it in C
Also after digging a little more I also came to know that running below program will not throw any error and will produce the output :

Program:
#include <stdio.h>
main()
{
 int j,i;
 int a[3];

       for(i=0;i<5;i++)
       scanf("%d",&a[i]);

     for (j = 0; j < 10; j++ )
   {
      printf("Element[%d] = %d\n", j,a[j] );
   }
     printf ("changed size: %d\n", sizeof(a) / sizeof(a[0]));
}

Output : 
Element[0] = 1
Element[1] = 2
Element[2] = 3
Element[3] = 4
Element[4] = 5
Element[5] = 0
Element[6] = -1585508667
Element[7] = 32734
Element[8] = 0
Element[9] = 0
changed size: 3

This is very strange as the length of the array is only three still I am able to assign the value to the array more than its length and yet there is no change in the length of the array and when I try to access values more than the size of its length it give me garbage

The Reason for above is explained below:

Actually in C there is no bound check available and which is the biggest drawback of it so when you will declare array it simply puts the values till its length and when you assign the values to the element more than its length it will overwrite those garbage values available in next memory addresses and display it when you print the array

Also one more important thing to note is that this behavior may lead to unusual termination of program or system hung because the values which we assign more than array size may overwrite the values of some critical system files available in those next memory blocks and it may lead to very serious issues... :)

2 comments:

  1. Hi Pritesh,

    There is a amazing explanation about all languages on ArrayIndexOutOfBoundsException. specially for C language it is also nice question for interview.

    ReplyDelete
    Replies
    1. Thanks Hardik...keep visiting for more interesting topics... :) :)

      Delete