下面在函数调用中使用指针是否是内存泄漏:
bson_t * parse_json(const char * json_fields){
bson_error_t error;
bson_t *bson_fields = bson_new_from_json((unsigned char *)json_fields, -1, &error);
if (!bson_fields) {
log_die("Error: %s\n", error.message);
} else {
return bson_fields;
}
log_die("Error: something bad happend in parse_columns");
return bson_fields; // this should never be reached ...
}
下面的代码可以工作,但是 parse_json
的指针在这里发生了什么?这是内存泄漏吗?
bson_concat(fields, parse_json(json_fields));
mongodb C-API 提供函数bson_destory
:
bson_destroy(fields);
我想知道显式释放 new_fields
的内存是否更好:
bson_t *new_fields = parse_json(json_fields);
bson_concat(fields, new_fields);
bson_destroy(new_fields);
虽然这个例子使用了 mongodb c-api,但我也在尝试理解一般情况。
some_type * pointer_returner(){
some_type *var;
...
return var;
}
do_something(pointer_retuner());
上面的调用是否导致内存泄漏?
最佳答案
是的,您需要调用 bson_destroy
来释放不再使用的结构对象。
来自 bson_destroy
documentation :
The bson_destroy() function shall free an allocated bson_t structure.
This function should always be called when you are done with a bson_t unless otherwise specified.
关于c - 在函数调用中使用从函数返回的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27594425/