C - using a pointer returned by a function in a function call

Is the following use of pointers in function calls 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? Is this a memory leak?

bson_concat(fields, parse_json(json_fields));

      

Mongodb C-API offers a function bson_destory

:

bson_destroy(fields);

      

I'm wondering, maybe it's better to explicitly free the memory new_fields

:

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

      

This example uses mongodb c-api, I am also trying to understand the general case.

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

  return var;
  }


  do_something(pointer_retuner());

      

Called a call that is leaking memory?

+3


source to share


1 answer


Yes, you need to call bson_destroy

to free the struct object, it is no longer used.

From bson_destroy

documentation :



The bson_destroy () function frees the allocated bson_t structure.

This function should always be called when you're done with bson_t, unless otherwise noted.

+3


source







All Articles