这个问题涉及到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_object_set_new
是专门为此而设计的。 - N. George