Why is there an infinite loop in my program?
arrays, c, for-loop, infinite-loop
Solution
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.
Problem
``` 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?