Accessing unallocated memory C++

前端 未结 6 1798
独厮守ぢ
独厮守ぢ 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:11

    Accessing unallocated memory is not guaranteed to throw exceptions.

    It's actually not guaranteed to do anything, since that's undefined behavior. Anything could happen. Beware of nasal demons.

    It prints 55 because you just stored 54, fetched it back and then printed 54+1. It's not at all guaranteed to print 55, although that's often what will happen in practice. This time it worked.

提交回复
热议问题