0

I am getting confused with an array code.

According to me the program should raise an error but it's working fine. The code :

#include<stdio.h>
#include<conio.h>

void main()
{
    int a[1],n,i;
    clrscr();
    printf("Enter the length");
    scanf("%d",&n);
    for( i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
    getch();
}

Here the array size is 1 but when I enter the length 5 then it works fine : the program show all 5 elements that i have entered.

This is the output screen.

JoeBilly
  • 3,057
  • 29
  • 35
Igeek01
  • 81
  • 1
  • 3

2 Answers2

3

Accessing array out of bounds causes undefined behavior. Anything can happen including the outcome you are observing. In this case you are overwriting some objects stored after the array. They are just not used in this particular case and your program doesn't crash.

Such bugs are really hard to debug. It works fine now, but might start to fail, for example, when different compiler is used. Memory analyzer can help detecting such bugs. It will detect some invalid memory accesses, even if they do not cause a crash.

Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65
  • Thank you very much...But i also tried to initialize the array explicitly and its work fine i.e if i used to declare elements out of index then it shows error.. For example " int a[1]={1,2,3,4,5,6}; ".. – Igeek01 Mar 14 '15 at 08:27
  • 1
    In that case both the size and number of elements are available at compile time. Compiler can easily verify them. In your first case the number of elements is only available after the program has been run. Unless you are using some specialized compiler, the size of the array is no longer available in compiled program - validation is left to the programmer. – Piotr Praszmo Mar 14 '15 at 08:39
1

When you have defined int a[1], only space for one int is allocated on the stack. Any access beyond array bound causes undefined behavior. Therefore, the code is wrong according to the C standard.

In your case, the program is accessing some space beyond the array and by the chance of luck you didn't end up yourself with a segmentation fault.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
  • 2
    I would say it is bad luck, because a segmentation fault signal would be much better than having _arbitrary user provided data overwriting the stack_ -- a situation which is sometimes referred to as **stack overflow**, by the way. You may have read that term somewhere. – Leonard Michlmayr Mar 14 '15 at 08:58