memory leak using cJson ESP32

Pedrojdi
Posts: 9
Joined: Mon Mar 08, 2021 2:14 pm

memory leak using cJson ESP32

Postby Pedrojdi » Tue Apr 13, 2021 9:22 pm

Please could someone help me to identify why there is a memory leak using cJson I could not find the problem. whenever I do an authentication the live memory decreases. The json is created only at that point, I have already changed the control logic but in any case it always ends up leaking memory

Code: Select all

esp_err_t loginWS(httpd_req_t *request) {
    JwtService jwtService;
    AutenticationModel autenticationModel;
    AutenticationService autenticationService;

    autenticationModel = autenticationService.loadRegister();

    cJSON *jsonWs;
    cJSON *params;

    std::string token = "";
    std::string msg = "";
    std::string body = "";
    std::string login = "";
    std::string password = "";
    bool error;

    body = _getBody(request); //json received

    jsonWs = cJSON_Parse(body.c_str());

    login = cJSON_GetObjectItem(jsonWs, "_login")->valuestring;
    password = cJSON_GetObjectItem(jsonWs, "_password")->valuestring;

    if (login == autenticacaoModel.getLogin() && senha == autenticacaoModel.getPassword()) {
        token = jwtService.criarJwt();
        msg = "";
        error = false;
    } else {
        token = "";
        msg = "Login or password invalid";
        error = true;
    }

    cJSON_AddItemToObject(jsonWs = cJSON_CreateObject(), "token", params = cJSON_CreateObject());
    cJSON_AddItemToObject(params, "token", cJSON_CreateString(token.c_str()));

    cJSON_AddItemToObject(jsonWs, "message", params = cJSON_CreateObject());
    cJSON_AddItemToObject(params, "error", cJSON_CreateBool(erro));
    cJSON_AddItemToObject(params, "msg", cJSON_CreateString(mensagem.c_str()));

    const char *texto = cJSON_Print(jsonWs);
    cJSON_Delete(jsonWs);

    httpd_resp_set_hdr(request, "Content-Type", "application/json");
    httpd_resp_sendstr(request, texto);

    free((void *)texto);

    return ESP_OK;
}

WiFive
Posts: 3529
Joined: Tue Dec 01, 2015 7:35 am

Re: memory leak using cJson ESP32

Postby WiFive » Tue Apr 13, 2021 9:53 pm

You did not free jsonWs before you reused it

Pedrojdi
Posts: 9
Joined: Mon Mar 08, 2021 2:14 pm

Re: memory leak using cJson ESP32

Postby Pedrojdi » Tue Apr 13, 2021 10:16 pm

good night colleague, how to release jsonWS using the command free(jsonWs);

In which part of the program I would release, because by placing this command the program restarts

thank you so much

WiFive
Posts: 3529
Joined: Tue Dec 01, 2015 7:35 am

Re: memory leak using cJson ESP32

Postby WiFive » Tue Apr 13, 2021 11:39 pm

Code: Select all

    jsonWs = cJSON_Parse(body.c_str());

    login = cJSON_GetObjectItem(jsonWs, "_login")->valuestring;
    password = cJSON_GetObjectItem(jsonWs, "_password")->valuestring;

    cJSON_Delete(jsonWs);

Who is online

Users browsing this forum: Bing [Bot], Google [Bot], Vineethad and 106 guests