简体   繁体   English

c - 使用函数调用中函数返回的指针

[英]c - using a pointer returned from function in a function call

Is the following usage of pointers in functions call is a memory leak: 函数调用中指针的以下用法是内存泄漏:

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 ...
}

The following code works, but what happens to the pointer from parse_json here? 下面的代码可以工作,但是这里的parse_json指针会发生什么? Is this a memory leak? 这是内存泄漏吗?

bson_concat(fields, parse_json(json_fields));

The mongodb C-API offers the function bson_destory : mongodb C-API提供了bson_destory函数:

bson_destroy(fields);

I am wondering maybe it's better to explicitly free the memory of new_fields : 我想知道明确释放new_fields的内存可能更好:

        bson_t *new_fields = parse_json(json_fields);
        bson_concat(fields, new_fields);
        bson_destroy(new_fields);

While this example uses mongodb c-api, I am also trying to understand the general case. 虽然这个例子使用mongodb c-api,但我也试图理解一般情况。

  some_type * pointer_returner(){
  some_type *var;
  ...

  return var;
  }


  do_something(pointer_retuner());

Is the call above causing a memory leak? 上面的调用会导致内存泄漏吗?

Yes, you need to call bson_destroy to deallocate your structure object it is no longer used. 是的,您需要调用bson_destroy来释放不再使用的结构对象。

From bson_destroy documentation : 来自bson_destroy 文档

The bson_destroy() function shall free an allocated bson_t structure. bson_destroy()函数应释放已分配的bson_t结构。

This function should always be called when you are done with a bson_t unless otherwise specified. 除非另有说明,否则应在使用bson_t时始终调用此函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM