Accessing unallocated memory C++

前端 未结 6 1794
独厮守ぢ
独厮守ぢ 2020-12-11 20:06

I am having this piece of code:

try
{
    int* myTestArray = new int[2];

    myTestArray[4] = 54;

    cout << \"Should throw ex \"  << myTestAr         


        
6条回答
  •  悲&欢浪女
    2020-12-11 20:09

    As others have said, this is undefined behavior, but I thought a bit more info might help. myTestArray is not an "Array" in the sense of a type, with special operators, etc. It is just a pointer to a location in memory. The expression myTestArray[4] is just short-hand for *(myTestArray+4) - it is returning a reference to the memory location that is 4 * sizeof(int) past myTestArray. If you want bounds checking, you'll have to use std::vector::at().

提交回复
热议问题