libfastjson
libfastjson copied to clipboard
Found a problem when using the same object in different objects
Found a problem when using the same object in different objects
fjson_object *m = fjson_object_new_object();
fjson_object *i = fjson_object_new_int(1);
fjson_object *a = fjson_object_new_object();
fjson_object_object_add(a, "i", i);
fjson_object *b = fjson_object_new_object();
fjson_object_object_add(b, "i", i);
fjson_object_object_add(m, "a", a);
fjson_object_object_add(m, "b", b);
printf("%s\n", fjson_object_to_json_string_ext(m, FJSON_TO_STRING_PLAIN));
fjson_object_put(m); // segmentation fault due to trying to delete one i in different objects
Because i can't be added twice for a and b. Once you use fjson_object_object_add(a, "i", i);
, the ownership of i is transfered to the obj a. If you wan to let b have the same i, you need to create a new one.
I fix you problem like this:
#include <stdio.h>
#include "json_object.h"
int main() {
fjson_object *m = fjson_object_new_object();
fjson_object *i = fjson_object_new_int(1);
fjson_object *a = fjson_object_new_object();
fjson_object_object_add(a, "i", i);
fjson_object *b = fjson_object_new_object();
i = fjson_object_new_int(1); // create a new i
fjson_object_object_add(b, "i", i);
fjson_object_object_add(m, "a", a);
fjson_object_object_add(m, "b", b);
printf("%s\n", fjson_object_to_json_string_ext(m, FJSON_TO_STRING_PLAIN));
fjson_object_put(m);
}
The output is ok:
$ ./test
{"a":{"i":1},"b":{"i":1}}