Memory leak using JSON-C

I am new to JSON-C, see my sample code and let me know, it will create a memory leak, if so, how to free the JSON-C object.

struct json_object *new_obj = NULL; new_obj = json_tokener_parse(strRawJSON); new_obj = json_object_object_get(new_obj, "FUU"); if(NULL == new_obj){ SYS_OUT("\nFUU not found in JSON"); return NO; } new_obj = json_object_object_get(new_obj, "FOO"); // I m re-using new_obj, without free it? if(NULL == new_obj){ SYS_OUT("\nFOO not found in JSON"); return NO; } // DO I need to clean new_obj, if yes then how ?? 

Do I need to clear new_obj, if so, how. Can someone help to understand how to manage JSON-C memory.

Thanks at Advance

+6
source share
2 answers

NOT. We need to call json_object_put only once for the root object, unless we explicitly allocate memory to the json object, and this worked for me ..... !!

+7
source

Yes, I believe your code will be a memory leak. The problem is that you rewrite your new_obj pointer several times. Your code should look something like this:

 struct json_object *new_obj, *fuu_obj, *foo_obj; new_obj = json_tokener_parse(strRawJSON); fuu_obj = json_object_object_get(new_obj, "FUU"); if(NULL == new_obj){ SYS_OUT("\nFUU not found in JSON"); return NO; } foo_obj = json_object_object_get(new_obj, "FOO"); if(NULL == new_obj){ SYS_OUT("\nFOO not found in JSON"); return NO; } json_object_put(foo_obj); json_object_put(fuu_obj); json_object_put(new_obj); 

Please let me know if this works for you. If you need more help, json-c has a link counting mode that can provide you with more information about objects. Let me know, and I can elaborate on this.

+5
source

Source: https://habr.com/ru/post/905212/


All Articles