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?
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?
I don't see any infinite loop condition, but you're setting up to 20 values on an array with 5 "slots"???
Here is what happenning in the given code.
in my stack memory I got the address locations as
i
is stored at location 0xbfd1048c addressand
array
is stored at location 0xbfd10478 addressAs you are incrementing
i
value for each loop at one point of time the address ofarray[i]
is equivalent to address ofi
(its just pointer dereferencing)So what you are storing at
array[i]
is nothing but thei
's instance address so you are over writing thei
's instance value to 0 as you have mentionedarray[i] = 0
which is equivalent toi=0
so the conditioni<=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.
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 assignarray[5]
.If you want to fix your program, change the loop to write to the correct number of elements