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?
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++)
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With