c++ - 内存删除的运行时检测

标签 c++ windows pointers memory-corruption

代码:

int *ptr = new int[10];
int *q = ptr;
delete q;

工作正常,没有任何问题(没有运行时错误)。

但是,下面的代码:

int *ptr = new int[10];
int *q = ptr;
q++;
delete q;

导致运行时错误。

我使用 Microsoft Visual Studio-8 和 Win-7 作为平台。

我无法弄清楚为什么在第二种情况下会出现运行时错误?

最佳答案

您的代码导致了未定义的行为。未定义的行为意味着任何事情都可能发生,无法定义行为。该程序的运行完全靠运气,它的行为无法解释。

基本上,

如果您使用new 分配动态内存,您必须使用delete 来释放它。

如果您使用 new[] 分配动态内存,您必须使用 delete[] 来释放它。

将任何地址传递给 delete 而不是由 new 返回的地址是未定义的行为。
这是来自标准的引述。

根据 C++03 标准 § 3.7.4.2-3:

If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_-t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t) or operator new[](std::size_t, const std::nothrow_t&) in the standard library.

在 C++ 中最好使用 RAII(SBRM) 通过使用智能指针而不是原始指针,它会自动处理内存释放。

关于c++ - 内存删除的运行时检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6890883/

相关文章:

c++ - 将我的 c++ 程序的数据保存在 linux 文件系统中的什么位置以便能够访问它?

c++ - priority_queue 的问题 - 在堆之后写入内存

c++ - 应用程序无法从 WinSxS 加载 Win32 程序集

php - 无法在 Windows 上安装 XDEBUG?

c - 将指针从一个函数传递到另一个函数

c# - 包含指向另一个 c++ 结构的指针的 c++ 结构的编码

c++ - 我如何在 std::vector<short> 中 push_back ShortBuffer 数据?

ios - 我的第一个 Visual Studio iOS 项目的问题

c# - 无法在 Windows 8.1 上实例化 System.Net.Http.HttpClientHandler

function - 如何在 Fortran 中给函数名起别名