c++ 如何修复内存访问越界(访问超出内存块上限)

lf5gs5x2  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(182)
int main()
{
    int n = 3;
    int a[n] = {1,2,3};

    ...
    in middle of code, value of n can be increased by 10 so I want to have check before cout otherwise       a[10] is out of bound.  
    ...

    cout<<a[n-1];
    return 0;
}

为了解决上述问题,我简单地把一个如果检查。
更正代码:

int main()
{
    int n = 3;
    int a[n] = {1,2,3};
    ...

    In middle of code, value of n can be increased by 10 so I want to have check before cout otherwise       a[10] is out of bound.   
    ...
    if(n<= 3)
    {
         cout<<a[n-1];    
    }
    return 0;
}

是否有其他方法可以避免内存访问越界
我试着用如果检查的基础上的大小。

8mmmxcuj

8mmmxcuj1#

int a[n] = {1,2,3};

可能是

a[0] = 1
a[1] = 2
a[2] = 3

如果n等于或小于-1,或者等于或大于3,则会有多余内存。
在读一[n]之前你可以查一下:

if ( 0 >= n & n < 3)
{
  // ....you can read a[n] 
}

相关问题