jansson json_decref unexpected behavior

885 Views Asked by At

I am using the jansson library for a C project.

I have some problem understanding how to use the decref. Shall it be used after each new json_t parameter or not? As I understand jansson will borrow references to make this simpler.

If I run this program and check the values of a_id and a_test they are the same. I expected error or null for a_test.

I tried the same idea but then I added decref for json_acc and json_param but it crashed before I could even read the 1:th value. I was assuming a crash but not until a_test.

This is part of a bigger project but I try to add an example to show the essentials.

API side:

json_t* parObj;

void loadFile(char* path)
{
    json_error_t error;
    parObj = json_load_file(path, 0, &error);
}

int getAccountId(char* id)
{
    json_t* json_acc = json_object_get(parObj, "accounts");
    json_t* json_param = json_object_get(json_acc, id);
    return json_integer_value(json_param);
}

void cleanJson()
{
    json_decref(parObj);
}

Caller side:

loadFile("/home/jacob/accountDump.json");
int a_id = getAccountId("10");
cleanJson();
int a_test = getAccountId("10");
1

There are 1 best solutions below

0
On BEST ANSWER

I did misunderstood how it is supposed to work, I assumed that decref would also set the memory to zero.

The API will remove the references and make it a free memory but as long as no one writes there or memset it to zero and the pointer is not set to null I can still read the values from that pointer.