删除在C的malloc分配的std :: String数组++ [英] Deleting an array of std::string allocated with malloc in C++

查看:299
本文介绍了删除在C的malloc分配的std :: String数组++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个从我的问题在跟进:在C ++

This is a follow up from my question at: Array of strings with malloc on C++

正如我已经实现了托尼·D溶液中,我分配的内存为的std ::字符串的数组与的malloc 然后创建了 STD:字符串为元素的每一个与新:

As I have implemented Tony D solution, I have allocated memory for an array of std::string with malloc and then created the std:string for each one of the elements with new according to:

void* TP = malloc(sizeof (string) * SS);
for (int i = 0; i < SS; i++) {
  new (&((string*)TP)[i]) std::string(Token[i]);
}

令牌矢量&lt;串&GT; SS INT

我知道这是不推荐的,我知道这是不优雅,我知道有
  对于这个数组的创建和填充许多其他解决方案,但我需要做的
  这种方式

I know this is not recommended, I know it is not elegant, I know there are many other solutions for this array creation and filling, but I need to do it this way

我现在遇到的问题是在阵列删除。当我创建每个的std ::字符串单独但是对于一个的malloc 阵列的配置,在我的析构函数我有写的:

The issue I encounter now is at the array deletion. As I create each std::string separately but the allocation for the array with a malloc, in my destructor I have written:

for (int i = 0; i < SS; i++) {
  delete (&((string*) TP)[i]);
}
free(TP);

但在运行时,在免费(TP)指责双自由和腐败。

通过注释免费(TP)我解决运行时的问题(hidding真正的问题),但我需要确保所有的内存被释放,因为这可能会导致在类中的内存泄漏。

By commenting the free(TP) I solve the issue for runtime (hidding the real issue), but I need to be sure all memory is released as this may cause a memory leak within the class.

那么,TP足够的各元素的删除以释放所有的存储器?从我的理解的malloc 自主分配的内存,它需要获得自由独立于的std ::字符串元素;但随后,为什么我得到这个错误?

So, is the deletion of each element of TP enough to free all that memory? From my understanding the malloc has allocated memory independently and it needs to be free independently from the std::string elements; but then, why do I get this error?

推荐答案

您正在做的一个位置,新来运行的std ::字符串的构造函数中的的malloc 分配的块,但你使用删除将运行析构函数,并尝试以释放内存(你不不想在这里做第二个,因为你与自由释放())。

You're doing a placement-new to run std::string's constructor on the malloc allocated block, but then you're using delete which will run the destructor AND try to free the memory (you don't want to do the second one here since you're freeing with free()).

您想手​​动运行析构函数,像这样...

You want to run the destructor manually, like this...

for (int i = 0; i < SS; i++) {
  (&((string*) TP)[i])->~string();
}
free(TP);

这篇关于删除在C的malloc分配的std :: String数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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