如何在函数中分配空闲内存

时间:2017-10-02 20:00:55

标签: c++ xgboost

我正在使用xgboost和C_API,我正试图在我的代码中找到内存泄漏源。 我有以下代码:

// xgboost / c_api.cc中的函数定义

XGB_DLL int XGBoosterPredict(BoosterHandle handle, 
DMatrixHandle dmat, 
int option_mask, 
unsigned ntree_limit, 
xgboost::bst_ulong *len, 
const bst_float **out_result)
{
  std::vector<bst_float>& preds = XGBAPIThreadLocalStore::Get()-
  >ret_vec_float;
  API_BEGIN();
  Booster *bst = static_cast<Booster*>(handle);
  bst->LazyInit();
  bst->learner()->Predict(
      static_cast<std::shared_ptr<DMatrix>*>(dmat)->get(),
      (option_mask & 1) != 0,
      &preds, ntree_limit,
      (option_mask & 2) != 0,
      (option_mask & 4) != 0);
  *out_result = dmlc::BeginPtr(preds);
  *len = static_cast<xgboost::bst_ulong>(preds.size());
  API_END();
}

//在调用XGBoosterPredict的主函数中 //正确定义了h_booster,h_test

const float *f;
XGBoosterPredict(h_booster, h_test, 0, 0, &out_len, &f);

//

在XGBoosterPredict中,以下内容分配给指针:

std::vector<bst_float>& preds = XGBAPIThreadLocalStore::Get()->ret_vec_float;
*out_result = dmlc::BeginPtr(preds);

问题:为f ??

分配释放内存的正确方法是什么

1 个答案:

答案 0 :(得分:0)

您并不打算免费*f

dmlc::BeginPtr(preds)安全地返回preds的地址,代表静态分配的内存(XGBAPIThreadLocalStore::Get()的内容),所以您不必担心关于在这里释放记忆。

看起来你的内存泄漏是由其他一些问题引起的。