json_decref不释放内存?
此问题与C的libjansson JSON API有关。json_decref不释放内存?,c,memory-leaks,C,Memory Leaks,此问题与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();
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;
}
这是因为由
json\u 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\u object\u set\u new
就是专门针对这一点的。