这个C ++代码会导致内存泄漏(转换数组新) [英] Will this C++ code cause a memory leak (casting array new)

查看:124
本文介绍了这个C ++代码会导致内存泄漏(转换数组新)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用一些使用可变长度结构(TAPI)的遗留C ++代码,其中结构大小将取决于可变长度字符串。结构通过转换数组 new 分配:



STRUCT * pStruct = *)new BYTE [sizeof(STRUCT)+ nPaddingSize];



稍后,使用删除调用:

  delete pStruct; 

这个数组的混合 new [] 和非数组 delete 导致内存泄漏或者它将取决于编译器?我会更好的改变这个代码使用 malloc 免费


<从技术上来说,我相信它可能导致分配器不匹配的问题,虽然在实践中我不知道任何编译器不会做正确的事情与这个例子。



更重要的是,如果 STRUCT 有一个析构函数,已经调用了相应的构造函数。



当然,如果你知道pStruct在哪里,为什么不直接转换为delete来匹配分配:

  delete [](BYTE *)pStruct; 


I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus:

STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];

Later on however the memory is freed using a delete call:

delete pStruct;

Will this mix of array new [] and non-array delete cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use malloc and free instead?

解决方案

Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.

More importantly if STRUCT where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.

Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:

delete [] (BYTE*) pStruct;

这篇关于这个C ++代码会导致内存泄漏(转换数组新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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