访问未分配的内存 C++ [英] Accessing unallocated memory C++

查看:46
本文介绍了访问未分配的内存 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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

    myTestArray[4] = 54;

    cout << "Should throw ex "  << myTestArray[4] + 1 << endl;
}
catch (exception& exception)
{ 
    cout << "Exception content: " << exception.what() << endl;
}

对我来说真正的古玩是为什么这里没有抛出异常,因为它访问了一个没有分配的索引......为什么 55 是 print ?是不是C++自动增加了数组的大小?

What is really curios for me, is that why the exception is not thrown here, since it was accessed an index which was not allocated... and why 55 is print ? Is that C++ automatically increased the size of the array ?

推荐答案

访问未分配的内存并不能保证抛出异常.

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.

它打印了 55,因为您刚刚存储了 54,取回它然后打印了 54+1.根本不能保证打印 55,尽管这在实践中经常会发生.这次成功了.

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.

这篇关于访问未分配的内存 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆