使用malloc,struct,std :: string和free可能导致内存泄漏 [英] Possible memory leak with malloc, struct, std::string, and free

查看:147
本文介绍了使用malloc,struct,std :: string和free可能导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到类似以下情况,并且不确定结构的std :: string元素是否泄漏内存或是否可以.

I've a situation like the following, and I'm not sure whether or not the std::string elements of the struct leak memory or if this is ok. Is the memory allocated by those two std::strings deleted when free(v) is called?

struct MyData
{
    std::string s1;
    std::string s2;
};

void* v = malloc(sizeof(MyData));

...

MyData* d = static_cast<MyData*>(v);
d->s1 = "asdf";
d->s2 = "1234";

...

free(v);

是否泄漏?

我使用空指针是因为我还有另一个上乘的结构,它由一个枚举和一个空指针组成.根据枚举变量的值,void *将指向不同的数据结构.

I'm using the void-pointer because I have another superior struct, which consists of an enum and a void-pointer. Depending on the value of the enum-variable, the void* will point to different data-structs.

示例:

枚举字段具有EnumValue01 => void指针将指向一个由malloc分配的MyData01结构

enum-field has EnumValue01 => void-pointer will point to a malloc'd MyData01 struct

枚举字段具有EnumValue02 => void指针将指向一个malloc分配的MyData02结构

enum-field has EnumValue02 => void-pointer will point to a malloc'd MyData02 struct

对于不同方法的建议,我们深表感谢.

Suggestions for different approaches are very appreciated, of course.

推荐答案

确实存在泄漏. free不会调用MyData析构函数(毕竟这是一个C函数,对C ++东西一无所知).您应该使用new/delete代替malloc/free:

There is a leak indeed. free doesn't call MyData destructor (after all it's a C function which doesn't know anything about C++ stuff). Either you should use new/delete instead of malloc/free:



MyData* d = new MyData;
d->s1 = "asdf";
d->s2 = "1234";
delete d;

或自己调用析构函数:



void* v = malloc(sizeof(MyData));
MyData* d = new (v) MyData; // use placement new instead of static_cast
d->s1 = "asdf";
d->s2 = "1234";
...
d->~MyData();
free(v);

如Sharptooth所指出的那样,如果不进行初始化,则不能直接将malloc分配的内存用作MyData结构,因此也必须自己完成.要使用已分配的内存初始化MyData,您需要使用new放置(请参见上面的代码).

as sharptooth noted you can't directly use memory allocated by malloc as a MyData struct without initialization, so you have to do it by yourself as well. To initialize MyData using already allocated memory you need to use placement new (see in the code above).

这篇关于使用malloc,struct,std :: string和free可能导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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