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;
}
It was because the json integer created by
json_integer(42)
was not freed, you need to free that object too:Also note
main
should beint main(void)
by the standard.