json_decref不释放内存?

4
这个问题涉及到C语言的libjansson JSON API。使用json_decref函数可以跟踪对json_t对象的引用次数,当引用次数达到0时,应释放已分配的内存。那么为什么这个程序会导致内存泄漏?我错过了什么吗?难道没有垃圾回收机制?
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个回答

3

由于json_integer(42)创建的 JSON 整数对象没有被释放,您需要释放该对象:

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

同时请注意,根据标准,main 应该是 int main(void)


谢谢!json_object_set_new 是专门为此而设计的。 - N. George

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接