Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there an infinite loop in my program?

int main(void)
{
    int i;
    int array[5];

    for (i = 0; i <= 20; i++)
    array[i] = 0;

    return 0;
}

Why is the above code stuck in an infinite loop?

like image 692
daNullSet Avatar asked Dec 24 '12 10:12

daNullSet


4 Answers

You declare an array with 5 elements but write 21 elements to it. Writing past the end of an array results in undefined behaviour. In you case, you're writing to the loop counter i, resetting it to 0, probably when you assign array[5].

If you want to fix your program, change the loop to write to the correct number of elements

int num_elems = sizeof(array) / sizeof(array[0]);
for (i = 0; i < num_elems ; i++)
like image 150
simonc Avatar answered Sep 24 '22 11:09

simonc


Here is what happenning in the given code.

#include<stdio.h>
#include<string.h>
int main(void)
{
    int i;
    int array[5];

    for (i = 0; i <= 20; i++)
    {
        printf("%p %p \n",&i,&array[i]);
        printf("the value of i is %d \n",i);
        sleep(1);
        array[i] = 0;
        printf("i may be modified here lets see what i is %d \n", i);
    }

    return 0;
}

in my stack memory I got the address locations as

i is stored at location 0xbfd1048c address

and array is stored at location 0xbfd10478 address

As you are incrementing i value for each loop at one point of time the address of array[i] is equivalent to address of i (its just pointer dereferencing)

So what you are storing at array[i] is nothing but the i's instance address so you are over writing the i's instance value to 0 as you have mentioned array[i] = 0 which is equivalent to i=0 so the condition i<=20 always succeeds.

Now the BIG question why does the memory allocated in such a way.

It is decided at run time and on the availability of the resources to the kernel.

So that's why we have to dwell with in the limits of the array.

like image 25
Abdul Muheedh Avatar answered Sep 25 '22 11:09

Abdul Muheedh


You are invoking undefined behaviour by overwriting beyond the memory you are allowed. So anything can happen.

Most likely, it's overwriting the loop counter.

like image 32
P.P Avatar answered Sep 22 '22 11:09

P.P


The problem is when you try to access an element outside the bounds of the array, which is only 5 big - but in a loop that is 21 big.

int main(void)
{
    int i;
    int array[5];

    for (i = 0; i < 5; i++)
    array[i] = 0;

    return 0;
}
like image 30
Fenton Avatar answered Sep 24 '22 11:09

Fenton