json_decref无法释放内存? [英] json_decref not freeing memory?
问题描述
此问题与C的libjansson JSON API有关.json_decref
函数用于跟踪对json_t
对象的引用数,并且当引用数达到0
时应释放分配的内存.那为什么这个程序会导致内存泄漏呢?我想念什么?仅仅是没有垃圾收集吗?
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;
}
推荐答案
这是因为json_integer(42)
创建的json整数未释放,因此您也需要释放该对象:
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;
}
还要注意,main
应该是标准的int main(void)
.
Also note main
should be int main(void)
by the standard.
这篇关于json_decref无法释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!