json_decref not freeing memory?

喜夏-厌秋 提交于 2020-01-15 06:25:33

问题


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.



来源:https://stackoverflow.com/questions/37018004/json-decref-not-freeing-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!