A detailed explanation of one of the reasons for the infinite loop caused by the array out of bounds in the C language

Let's take a look at this code first (VS development environment):

#include <stdio.h>
int main()
{
    int i = 0;
    int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
    for (i = 0; i <= 12; i++)
    {
        arr[i] = 0;
        printf("hello\n");
    }
    return 0;
}

Can you guess what the final output is in the VS development environment, is it outputting 13 hellos or a compilation error or something else? Forget it, the answer is revealed, it is an infinite loop, and countless hellos are output. Why is this happening, let me explain it in detail next~

Through debugging, we can find that the value of arr[12] is always the same as the value of i, which means that when arr[12] changes, i will also change, and vice versa:

 

 Seeing this, we might as well guess whether the addresses of the two are the same, otherwise why would you change me? By looking at the addresses of the two, I found that they are really the same!

? ? ? why? ? ?

 Before talking about it, we must first know that in this program, the i and arr arrays are local variables, and local variables are stored in the stack area.

The usage of stack is to allocate the space at the high address first, and then allocate the space at the low address according to the order in which the variables are defined in the code, and the address of the array gradually increases with the increase of the subscript. The following figure can simply represent what has been said above:

 As shown in the figure, if the space between i and the arr array is appropriate, it is possible that the arr array used may access i backwards, causing the value of i to be changed when a certain value in the arr array changes, which is very easy cause an infinite loop.

Finally, I would like to add that the running result of the above code is strictly dependent on the environment of the compilation environment, and the final result may also be different. For example, in VC6.0, i and arr are continuous, and there is no space in between. There is a space between i and arr in gcc. In VS2010, 2013, 2019, etc., there are 2 spaces between i and arr, which is the case above. So, in order to avoid all kinds of unpredictable situations, you better pay attention when writing programs, don't let the array access out of bounds~~

Guess you like

Origin blog.csdn.net/m0_63039919/article/details/121479389