[C Language]--What should I do if there is an infinite loop?

#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;
}

Reading the above code, we will think that this is not a simple array access out of bounds. Then this code should report an error, and then I run it with VS to see if the result is really the case?

VS 32 bit

VS 64 bit

 

 It can be seen from the above that the results of this code on different operating systems on VS are different, and not all errors will be reported. The reason is that it has to do with how addresses are allocated in memory.

32-bit memory is allocated from high address to low address. Since int i = 0 is created before array arr, the address of variable i is higher than the address of array arr. And because an array is stored from low address to high address internally. Therefore, the further back the array is stored, the higher its address. The a[12] of this code happens to point to the address of i, so that i is changed to 0 again, so it has been endlessly looping.

64-bit memory development is from low address to high address, so the array will cross the boundary.

The following are the steps to debug and check the memory in VS. It is very helpful to debug some code problems proficiently. So don't panic if you encounter problems with the code, debug it first.

 

Guess you like

Origin blog.csdn.net/m0_73381672/article/details/131315650