Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cJSON_Print memory leak #764

Closed
earlysun030201 opened this issue Jun 10, 2023 · 1 comment
Closed

cJSON_Print memory leak #764

earlysun030201 opened this issue Jun 10, 2023 · 1 comment

Comments

@earlysun030201
Copy link

earlysun030201 commented Jun 10, 2023

I'm using the latest version of the cJSON library, and when I calling cJSON_Print, it results in a memory leak.
C 17 Standard:

extern "C" {
#include "cJSON/cJSON.h"
}
#include <iostream>

int main() {
    while (getchar() == 10) {
        cJSON* json = cJSON_Parse(R"({
        "name": "test",
        "available":    true
        })");
        std::cout << cJSON_Print(json) << std::endl;
        cJSON_Delete(json);
    }
    return 0;
}

image
In the memory viewer, it can be observed that a new instance is created every time the contents within the loop are called.
image
When I remove the invocation of the cJSON_Print function, this issue disappears.

@7aman
Copy link

7aman commented Jun 11, 2023

cJSON_Print returns a heap allocated string (null terminated character array). it must be freed later.

extern "C" {
#include "cJSON/cJSON.h"
}
#include <iostream>

int main() {
    while (getchar() == 10) {
        cJSON* json = cJSON_Parse(R"({
        "name": "test",
        "available":    true
        })");
        char *json_str = cJSON_Print(json);
        cJSON_Delete(json);
        std::cout << json_str << std::endl;
       free( json_str );       
    }
    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants