Alex Rivera | Logout

Why is there an infinite loop in my program?

Asked 2012-12-24T10:55:40.733
11
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?

Edit
Report

1 Answer

20

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++)
answered 2012-12-24T10:57:22.233

Your Answer