代码:
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 operatornew(std::size_t)
oroperator new(std::size_t, const std::nothrow_-t&)
in the standard library, and the value supplied to operatordelete[](void*)
in the standard library shall be one of the values returned by a previous invocation of eitheroperator new[](std::size_t)
oroperator new[](std::size_t, const std::nothrow_t&)
in the standard library.
在 C++ 中最好使用 RAII(SBRM) 通过使用智能指针而不是原始指针,它会自动处理内存释放。
关于c++ - 内存删除的运行时检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6890883/