riaqn
riaqn

Reputation: 117

When json-c json_object_to_json_string release the memory

I am using json-c library to send json-object to client.And I notice there is no native function to release the memory which json_object_to_json_string allocate.Does the library release it automaticlly? OR I have to "free(str)" to avoid memory leak? I tried to read its source code but it makes me unconscious...So anybody know this?

Upvotes: 6

Views: 6290

Answers (1)

selalerer
selalerer

Reputation: 3924

It seems that you don't need to free it manually.

I see that this buffer comes from within the json_object (see the last line of this function):

const char* json_object_to_json_string_ext(struct json_object *jso, int flags)
{
    if (!jso)
        return "null";

    if ((!jso->_pb) && !(jso->_pb = printbuf_new()))
        return NULL;

    printbuf_reset(jso->_pb);

    if(jso->_to_json_string(jso, jso->_pb, 0, flags) < 0)
        return NULL;

    return jso->_pb->buf;
}

The delete function frees this buffer:

static void json_object_generic_delete(struct json_object* jso)
{
#ifdef REFCOUNT_DEBUG
  MC_DEBUG("json_object_delete_%s: %p\n",
       json_type_to_name(jso->o_type), jso);
  lh_table_delete(json_object_table, jso);
#endif /* REFCOUNT_DEBUG */
  printbuf_free(jso->_pb);
  free(jso);
}

It is important to understand that this buffer is only valid while the object is valid. If the object reaches 0 reference count, the string is also freed and if you are using it after it is freed the results are unpredictable.

Upvotes: 5

Related Questions