我有一个 for 循环,在迭代循环时,如果索引甚至是索引,则必须释放 json 对象,并且必须再次构造一个新对象,并且必须再次重复该过程。
同样,使用以下脚本,
#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);
}
}
}
如何使用 jansson json 对象构造并在索引为偶数索引时清除其内存来实现以下结果?
{"10":0,"20":1}
{"10":2,"40":3}
{"10":4,"60":5}
{"10":6,"80":7}
{"10":8,"100":9}
而现在,上面的脚本给出了以下响应,
{"10": 0}
Segmentation fault (core dumped)