当前位置:网站首页>A detailed explanation of one of the causes of dead loop caused by array out of bounds in C language

A detailed explanation of one of the causes of dead loop caused by array out of bounds in C language

2022-06-11 07:44:00 Fried tomatoes 110

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

You can guess at VS What is the final output of the development environment , It's output 13 individual hello Or compile and report errors or something else ? Forget it , The answer is announced. , It's a dead circle , Output numerous hello. Why is this so , Let me explain it carefully ~

By debugging , We can find out arr[12] The value of is always the same as i The value of is the same , That is to say, when arr[12] When the change ,i It's going to change , And vice versa :

 

  Here we can guess whether the addresses of the two are the same , Otherwise, why would you change me ? By looking at the addresses of both , Found that it was really the same !

??? Why? ???

  Before we talk , We need to know first , In this program ,i and arr Arrays are local variables , Local variables are stored in the stack area .

The habit of using stack is to define variables in the order of code , Allocate space at the high address first , Reallocate the space at the lower address , The array grows with the subscript , The address is getting bigger . The following figure can simply show the above contents :

  Pictured , If i and arr If the space between arrays is appropriate , It is possible to use arr The array was accessed backward out of bounds i, Lead to arr When a value in the array changes i The value of is also changed , This can easily lead to a dead cycle .

Finally, I would like to add , The running result of the above code is that the environment is strictly dependent on the compilation environment , The final result may be different . For example VC6.0 in ,i and arr Is a continuous , No space in the middle . stay gcc in i and arr There is a space between . stay VS2010,2013,2019 Wait ,i and arr There are 2 Space , That is, the situation mentioned above . So! , In order to avoid all kinds of unpredictable situations , You'd better pay attention when you write the program , Don't let the array access beyond the bounds ~~

原网站

版权声明
本文为[Fried tomatoes 110]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020519105897.html