json_decref没有释放内存?

此问题与用于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; } 

这是因为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)