I have been struggling to understand the proper use of json_decref and json_incref in combination with the json_get functions to isolate and manipulate a small piece of a larger json file without keeping the whole thing in memory. This question is in the context of the jansson.h library and the C programming language.
My question is, have I done the right thing here? In this function blockload below, am I using json_incref and json_decref in the orthodox way? I'm asking because I'm having trouble parsing what was said in the jansson documentation about json_incref and also in another posting here.
I have been struggling to understand the proper use of json_decref and json_incref in combination with the json_get functions to isolate and manipulate a small piece of a larger json file without keeping the whole thing in memory. This question is in the context of the jansson.h library and the C programming language.
My question is, have I done the right thing here? In this function blockload below, am I using json_incref and json_decref in the orthodox way? I'm asking because I'm having trouble parsing what was said in the jansson documentation about json_incref and also in another posting here.
The following code snippet reads in a file called "file.json" that has the data
{"myarray" : [[["aaa","aab","aac"],["aba","abb","abc"],["aca","acb","acc"] ],[["baa","bab","bac"],["bba","bbb","bbc"],["bca","bcb","bcc"] ],[["caa","cab","cac"],["cba","cbb","cbc"],["cca","ccb","ccc"] ]]}
The code snippet is as follows
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <jansson.h>
#define INPUTFILE "./file.json"
json_t *blockload(char *inputfile, char *blockname);
int main(void){
json_error_t error;
json_t *test;
int length;
const char *mystring_const;
json_t *myarray;
json_t *myelement;
myarray = blockload(INPUTFILE, "myarray");
myelement =json_array_get(json_array_get(json_array_get(myarray, 0), 0), 0);
mystring_const = json_string_value(myelement);
printf("%s \n", mystring_const);
json_decref(myarray);
return(0);
}
json_t *blockload(char *inputfile, char *blockname){
json_error_t error;
json_t *test, *myarray;
test = json_load_file(INPUTFILE, 0, &error);
myarray = json_object_get(test, blockname);
json_incref(myarray);
json_decref(test);
return(myarray);
}
In this case, I am trying to look at the array associated with the object "myarray", but one could imagine the json file has many more pieces, and I don't want to have to store them all in memory while I work with the array. I also don't want to clutter up the main routine with the details of how I load in this array of interest, so I have written this function blockload to hide the clutter.
While this code compiles and gives the answer I expect and produces no problems from valgrind, I'm worried it may still contain some memory use issues. So I'm asking the experts...