Why is there an infinite loop in my program?

2019-02-12 17:32发布

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?

5条回答
我只想做你的唯一
2楼-- · 2019-02-12 17:51

I don't see any infinite loop condition, but you're setting up to 20 values on an array with 5 "slots"???

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-12 17:53

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.

查看更多
Melony?
4楼-- · 2019-02-12 17:54

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.

查看更多
地球回转人心会变
5楼-- · 2019-02-12 18:01

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;
}
查看更多
爷、活的狠高调
6楼-- · 2019-02-12 18:02

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++)
查看更多
登录 后发表回答