简体   繁体   English

使用delete []和new(放置)运算符的Visual C ++堆损坏错误

[英]Visual C++ heap corruption error using delete [] and new (placement) operators

Code snippet: 程式码片段:

#include <new>
char buffer[512];

int main()
{
   double *pd;
   pd = new (buffer) double[5];
   delete [] pd;
   return 0;
}

This only hangs when using the placement new form of the new operator. 仅在使用new运算符的placement new表单时挂起。

I'm using the following tools and options: 我正在使用以下工具和选项:

> cl -EHsc foobar.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.21005
Microsoft (R) Incremental Linker Version 12.00.21005.1
pd = new (buffer) double[5];

What you are doing there is reusing the memory that buffer occupied to create an array of double. 您正在执行的操作是重用buffer占用的内存以创建一个double数组。 So now you are deleting a memory that you didn't not allocate with new . 因此,现在您将删除未分配给new的内存。

Don't do that. 不要那样做 The program didn't allocate the memory with operator new or operator new[] , so shouldn't delete it. 该程序未使用operator newoperator new[]分配内存,因此不应删除它。

You did not allocate that memory, so you should not try to free it (with delete [] ). 您没有分配该内存,因此不应尝试释放它(使用delete [] )。

In general, you would run the destructors: 通常,您将运行析构函数:

for( i = 0; i < 5; i++ ) {
    T* p = pd + i;
    p->~T();
}

But for double that isn't necessary. 但是对于double ,则没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM