I have a for loop and while iterating the loop, if the index is even index the json object has to be freed and again a new object has to be constructed and again the process has to be repeated.
For the same, using the below script,
#include <stdio.h>
#include <string.h>
#include <jansson.h>
int main(void) {
char* s = NULL;
json_t *root = json_object();
int myNum[10] = {10, 20, 10, 40, 10, 60, 10, 80, 10, 100};
for(int i=0; i<10;i++)
{
if(i%2==0)
{
json_t *root = json_object();
}
char *key = (char*)malloc(2);
snprintf(key, sizeof(key), "%d", myNum[i]);
json_object_set_new( root, key, json_integer(i));
s = json_dumps(root, 0);
puts(s);
if(i%2==0){
json_decref(root);
//free(s);
}
}
}
How to achieve the below result using jansson json object construction and clearing its memory when the index is even index?
{"10":0,"20":1}
{"10":2,"40":3}
{"10":4,"60":5}
{"10":6,"80":7}
{"10":8,"100":9}
Whereas now, the above script gives the below response,
{"10": 0}
Segmentation fault (core dumped)