Array access limit check

  • When c++ accesses an array, no matter whether it is accessed by subscript or pointer, it will not be checked for bounds, even if the access exceeds the bounds of the array.
  • The following code defines an array with a length of 7. When the number of accesses exceeds 7, the execution program compiler will not report an error.
int a[7] = {
    
     0,1,2,3,4,5,6 };
int a7=1, a8=1;

int main()
{
    
    
    int i;

    cout << "数组各个元素的地址" << endl;
    for (i = 0; i < 9; i++)
    {
    
    
        cout << "a[" << i << "]的地址为" << (a + i) << endl;
    }
    cout << "a7的地址为" << &a7 << endl;
    cout << "a8的地址为" << &a8 << endl;
    cout << endl;

    cout << "以下标方式访问数组" << endl;
    for (i = 0; i < 9; i++)
    {
    
    
        cout << "a["<< i << "]=" << a[i] << " ";
    }
    cout << endl;
    cout << endl;

    cout << "以下标方式访问数组" << endl;
    for (i = 0; i < 9; i++)
    {
    
    
        cout << "a[" << i << "]=" << *(a+i) << " ";
    }
    cout << endl;
    cout << endl;

    cout << "未超限写数组之前a7和a8的数据" << endl;
    cout << "a7=" << a7 << endl;
    cout << "a8=" << a8 << endl;
    cout << endl;

    cout << "超限写数组...." << endl;
    for (i = 0; i < 9; i++)
    {
    
    
        a[i] = i;
    }
    cout << endl;

    cout << "超限写数组之后a7和a8的数据" << endl;
    cout << "a7=" << a7 << endl;
    cout << "a8=" << a8 << endl;
 }

The execution result is as follows: the
Array access exceeded
overrun a[7] and a[8] and the defined int type a7, a8 variable addresses are the same, when the overrun access to a[7] and a[8], the data read out is Same as the initialization data of a7 and a8. When the data of the array is overwritten, the data of a[7] and a[8] is overwritten to change the data of variables a7 and a8.

  • Summary: 1. The c++ compiler will not check the over-limit reading and writing of the array, the data of the over-limit access to the array may get unexpected data, and the over-limit writing of the data of the array may change the data of other variables, thus the program It may not behave as expected; 2. The subscript access to the array is essentially using pointer access, the array name is the first address, and the subscript is the offset of the address (personal understanding, please point out the error).

Guess you like

Origin blog.csdn.net/qq_36439722/article/details/105307732