[英]How to free memory allocated in a function without returning its pointer?
[英]Howto free memory allocated in a function
我将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分配的内存的正确方法是什么?
您无意释放*f
。
dmlc::BeginPtr(preds)
安全返回的地址preds
,它代表静态分配的内存(这就是XGBAPIThreadLocalStore::Get()
一样),所以你不必担心在这里释放内存。
看来您的内存泄漏是由其他问题引起的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.