[C language] Analysis of infinite loop output caused by array crossing in vs2019

This experiment is carried out in the vs2019 X86 environment

This experiment analyzes a situation where an array out of bounds leads to an infinite loop of output.

The experimental code is as follows:

int main()
{
	int i = 0;
	int a[10] = { 1,2,3,4,5,6,7,8,9,10 };
	for (i = 0; i <= 12; i++)
	{
		a[i] = 0;
		printf("%d\n", a[i]);
	}
	return 0;
}

From the point of view of the code, the array is out of bounds in the loop. If you do not analyze the code from the perspective of the physical address, you will think that the output starts with address a and outputs 13 0s, but the actual situation is as follows, which is actually an infinite loop output 0, as shown below:

 

Why is this so?

The most critical of them is " in the space allocated by the program, the high address is used first and then the low address is used ". According to the usage rules of this space, in this program, i is created first, and the array a is created later, so the address of i is greater than the address of the end of a, if the range of a out of bounds includes i, then It will reassign i to 0, so that the value of i is always less than 12, resulting in an infinite loop.

ok! The theory is like this, and then experiment to see if it is what I expected:

 See that the address of i is the same as the address of a[12], so when i is equal to 12, i will be set to 0 because of the operation of a[12]=0, making it impossible for i to be greater than 12 , resulting in an endless loop.

 

When it is out of bounds, the experiment found that a[i]=0 will also change the content of the out-of-bounds space, so the out-of-bounds operation of the array is very dangerous.

Stupid little thoughts:

As mentioned above, in the space allocated by the program, the high address is used first and then the low address is used. If the variable i is created after the array, that is, the out-of-bounds space will not contain i, and i will not be changed by a[i] value, what happens?

The result is as follows:

Output 13 0s, and report an error directly, but why didn’t there be an error when there was an infinite loop before? Personally, I think that the error report was reported at the end of the program, but the previous one has been in an endless loop, and the program has no chance to report an error.

Guess you like

Origin blog.csdn.net/peng_lv/article/details/128111488