akheron / jansson

C library for encoding, decoding and manipulating JSON data
http://www.digip.org/jansson/
Other
3.05k stars 809 forks source link

jansson -2.7 #575

Closed hiallo closed 3 years ago

hiallo commented 3 years ago
#include <stdio.h>
#include <stdlib.h>
#include <jansson.h>

int test_jansson()
{
    json_t * root;

    json_set_alloc_funcs(malloc,free);

    root = json_pack("{s:s,s:s,s:[s,s]}","name","test","mac","F5:5b:3E:4F",\ 
                            "url","baidu.com","taobao.com");

    char * json  = json_dumps(root,JSON_MAX_INDENT);
    printf("%s\n",json);

    //ref 1 
    printf("ref %ld \n",root->refcount);
    json_decref(root);
    //decref 94603901829136
    printf("decref %ld \n",root->refcount);
    json_delete(root);
    if(json){
        printf("%s\n",json);
    }
    return 0;
}

result:

develop@203b75c2cd37:~/workspace/work/linux$ ./main 
{
                               "name": "test",
                               "mac": "F5:5b:3E:4F",
                               "url": [
                                                              "baidu.com",
                                                              "taobao.com"
                               ]
}
ref 1 
decref 94520736661520 
{
                               "name": "test",
                               "mac": "F5:5b:3E:4F",
                               "url": [
                                                              "baidu.com",
                                                              "taobao.com"
                               ]
}
develop@203b75c2cd37:~/workspace/work/linux$ 

After use json_decref and json_delete,I printf(json) have no error,why?

akheron commented 3 years ago

Don’t call json_delete, it’s done automatically when refcount drops to 0. The memory contents are still intact, but accessing the freed memory is an error nevertheless.

akheron commented 3 years ago

Also, it’s your responsibility to free() the string returned by json_dump. It’s not managed with root.

hiallo commented 3 years ago

ok ,thanks