从 C++ 到 C 释放 unique_ptr 时如何避免内存泄漏

Cop*_*OfA 2 c++ free unique-ptr delete-operator

我有一个 C 程序,它调用一个大型 C++ 库的 C++ 包装器。C++ 库的功能之一是提供一些预测,这些预测将在 C 中使用。我想知道我应该在哪里freedelete内存中。这是一些示例代码。

cpp_wrapper.cpp

#include "cpp_wrapper.h"


uint8_t * run_model(struct_with_model model_struct, const double * input_data) {
  // the model_struct is new'd in C++ in an earlier method

  // I have a method to convert the input data to std::vector for use in C++ code
  std::vector<double> data = get_data(input_data); 

  model_struct->model->LoadData(data);

  model_struct->model->run();

  std::vector<uint8_t> predictions = model_struct->model->GetPredictions();

  std::unique_ptr<uint8_t[]> classValues (new uint8_t[predictions.size()]);

  memcpy(classValues.get(), predictions.data(), sizeof(uint8_t) * predictions.size());

  model_struct->model->ClearData(); //clears data from model for future runs, if necessary

  return classValues.release()
}

void model_delete(model_struct) {
  // method to delete the model_struct when necessary
  delete model_struct;
}
Run Code Online (Sandbox Code Playgroud)

我有一个cpp_wrapper.h头文件,它声明了这些函数并extern C根据需要进行调用。在C端,c_code.c

#include "cpp_wrapper.h"


/*
   There's a bunch of code here for ingesting data, initializing the model_struct, etc
*/

uint8_t * predictions = run_model(model_struct, input_data);

// Do stuff with predictions, as necessary

model_delete(model_struct);

free(predictions); // HERE is the question
Run Code Online (Sandbox Code Playgroud)

我是C++ 代码中的new初始变量,但我是C++ 函数的返回值。我的理解是,当我将内存转移到C时,C代码负责内存。是这样吗?我是否应该有一个 C++ 方法来删​​除变量(从 C),就像我有一个 C++ 方法来删​​除变量一样?我对如何最好地管理这里的内存感到困惑。建议我不要在 C++ 中使用(或),但由于我将值传递回 C,也许这是一个更好的选择...?我不知道。classValuesreleasestd::unique_ptrrun_modelreleasefreepredictionsmodel_structmalloccalloc

Ben*_*uch 5

最简单的解决方案是将 C++ 调用分为两个调用。第一个确定需要的缓冲区有多大。然后就可以在C部分分配内存了。在第二次调用中,数据被复制到该缓冲区中。这样内存管理就完全保留在C 部分了。

或者,C++ 接口必须提供清除内存的函数。当要释放内存时,C 代码会调用此函数。通常的规则适用:

  • malloc->free
  • new->delete
  • new[]->delete[]

如果我正确地看到这一点,那么您目前正在实施第二种方法,但错误地使用了new[]-> delete

  • 是的,我实际上是在做混音。我在 C++ 中“new[]”了一个数组,将该数组“释放”到 C,然后使用 C“释放”该数组。我想我可能会使用第二种替代方案和 C++ 方法,例如“void delete_predictions(uint8_t * Predictions) {delete[] Predictions;}”。 (2认同)
  • 凡创造某物的人,也应对毁灭它负责。如果内存是在 C++ 部分分配的,那么 C++ 部分必须向 C 部分提供“dispose”方法。如果内存分配发生在C端,那么C端必须释放它。 (2认同)