Should the return value of cJSON_Print() be freed by the caller?
Asked Answered
M

2

3

I am using the cJSON library and I have a function as follows:

void printJsonObject(cJSON *item)
{
    char *json_string = cJSON_Print(item);
    printf("%s\n", json_string);
}

Will this function leak memory?

Mud answered 10/12, 2014 at 6:13 Comment(1)
possible duplicate of cJSON memory leakLabialize
C
7

I've never used cJSON , but as per the function definition present in this link, it looks like

char *cJSON_Print(cJSON *item)  {return print_value(item,0,1);} 

and

static char *print_value(cJSON *item,int depth,int fmt);

From print_value() function, the pointer returned is allocated by cJSON_strdup() [which is a modified version of the combination of malloc() and memcpy()] and it is returned to the caller.

As I see no method to track the allocation, IMO, the allocated memory needs to be free()d by the caller function. Otherwise, it will be a memory leak.

Crumpton answered 10/12, 2014 at 6:24 Comment(1)
This was correct at the time, however the correct API is now cJSON_free.Basile
B
4

Yes, it is a memory leak.

Buffers returned by cJSON_Print must be freed by the caller. Please use the proper API (cJSON_free) rather than directly calling stdlib free.

See the cJSON maintainer's comment: https://github.com/DaveGamble/cJSON/issues/5#issuecomment-298469697


I recommend:

void printJsonObject(cJSON *item)
{
    char *json_string = cJSON_Print(item);
    if (json_string) 
    {
        printf("%s\n", json_string);
        cJSON_free(json_string);
    }
}
Basile answered 7/7, 2018 at 18:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.