【问题标题】:free std::string member of a struct allocated using malloc使用 malloc 分配的结构的空闲 std::string 成员
【发布时间】:2023-02-11 14:46:22
【问题描述】:

我正在写一个 C++ 代码。作为其中的一部分,我使用了 C 库 quickjs。 这个库允许使用它的自定义 js_mallocz 调用(内部使用 malloc)创建动态内存,并在稍后使用 js_free 调用释放它。

我有这样的结构:

struct Person{
std::string id;
unsigned short age;
};

这是我使用 js_mallocz 调用创建的,使用正确的调用可以释放它。

//while assigning
auto person = (Person*) js_mallocz(ctx,sizeof(Person));
sole::uuid u4 =sole::uuid4();
std::string u = u4.base62();
person->id=u;
person->age=40;

//while freeing
js_free(ctx,person);

像这样的代码会给出如下错误:

24 bytes in 1 blocks are definitely lost in loss record 1 of 2
==30236==    at 0x483BE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==30236==    by 0x49D93FE: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_assign(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.29)
==30236==    by 0x11F93B: assign (basic_string.h:1370)
==30236==    by 0x11F93B: operator= (basic_string.h:700)

我不能使用 new 运算符,因为我需要使用第三方库 quickjs 完成的内存分配。如何在使用 malloc 创建的此类结构中释放一个 std::string ?

【问题讨论】:

  • malloc 不会调用构造函数。查找新位置:https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new
  • 不要在 C++ 中使用 malloc。只是不要。
  • 如果您需要malloc,请按照@drescherjm 的完整评论进行操作。请注意,您发现了一个有趣的情况,您必须手动调用实例的析构函数。很高兴。
  • std::string 既不是普通的默认构造的,也不是普通的可破坏的。所以如果只是使用malloc分配内存,将无法在分配的内存中创建Person类型的对象。 (请注意,有些类型的对象可以隐式创建,即隐式生命周期类型。)因此person-&gt;id = u 将尝试分配给不存在的对象。即使成功,js_free 也不会正确销毁对象,因为未调用析构函数。

标签: c++


【解决方案1】:

Placement new 是解决这个问题的方法。 (根据来自@drescherjm 的 cmets 得出结论) 所以代码应该是:

//while assigning
auto person = (Person*) js_mallocz(ctx,sizeof(Person));
person = new(person) Person(); //Placement new 
sole::uuid u4 =sole::uuid4();
std::string u = u4.base62();
person->id=u;
person->age=40;

//while freeing
person->~Person(); //Manually call destructor
js_free(ctx,person);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多