json_decref not freeing memory?

2019-07-16 13:50发布

问题:

This question relates to the libjansson JSON API for C. The json_decref function is to be used to keep track of the number of references to a json_t object and when the number of references reaches 0, should free the memory that was allocated. Then why does this program cause a memory leak? What am I missing? Is it just that there is no garbage collection?

int main() {
    json_t *obj;
    long int i;

    while(1) {
        // Create a new json_object
        obj = json_object();

        // Add one key-value pair
        json_object_set(obj, "Key", json_integer(42));

        // Reduce reference count and because there is only one reference so
        // far, this should free the memory.
        json_decref(obj);
    }

    return 0;
}

回答1:

It was because the json integer created by json_integer(42) was not freed, you need to free that object too:

int main(void) {
    json_t *obj, *t;
    long int i;

    while(1) {
        // Create a new json_object
        obj = json_object();

        // Add one key-value pair
        t = json_integer(42);
        json_object_set(obj, "Key", t);

        // Reduce reference count and because there is only one reference so
        // far, this should free the memory.
        json_decref(t);
        json_decref(obj);
    }

    return 0;
}

Also note main should be int main(void) by the standard.