ESP32 – Free memory occupied by JSON objects

It is quite possible that in your project involving interactions with a server, you would receive a JSON object from the server, parse it and do some processing. You may do this again and again. Alternatively, you may construct a JSON object and send it to the server in API calls. Again, you might do this again and again.

You might be re-writing the same global variable during each server transaction. However, you may observe (especially if your application is resource heavy) that after a certain number of transactions with the server, you run out of memory. Why does this happen? Well, the answer is memory leaks.

The JSON library you are using (ArduinoJson on Arduino platform, or cJSON on IDF platform) requires you to clean up the memory used by the JSON as soon as you are done with that object. Simply overwriting that object doesn’t recycle the memory. It creates a new object and the previous object remains there, occupying some memory.

So how do you free up the memory? Let’s look at the steps for both the Arduino platform and the IDF platform

Arduino

With Arduino, it is quite likely that you are using the ArduinoJson library. It has a straightforward clear() function that you should call as soon as you are done with the operations on the doc.

For example:

#include <ArduinoJson.h>
StatisJsonDocument<1024> my_doc;

void setup(){
Serial.begin(9600);
//Do the other setup stuff
}

void loop(){
//Populate my_doc

//Check memory usage of my_doc
//This will keep increasing in every iteration
//if you don't clear the object
Serial.println(my_doc.memoryUsage());

//Make all operations with my_doc

//Free up the space
my_doc.clear()
}

ESP-IDF

On the ESP-IDF platform, you’ll most likely use the cJSON library. Over here, you need to call the cJSON_Delete() function for every JSON object that you populate using cJSON_Parse() or create using cJSON_CreateObject(). If you are converting a JSON to a character array using cJSON_Print(), then the memory utilized by that array needs to be freed using the free() function.

An example can be found below:

cJSON *my_json;
char *my_char_array;

void json_ops(){
my_json = cJSON_CreateObject();

//Populate my_json

//Convert my_json to char array, for sending in an API perhaps
my_char_array = cJSON_Print(my_json);

//Perform other operations with my_json and/or my_char_array

//Free the memory
cJSON_Delete(my_json);
free(my_char_array);
}

For more tutorials on ESP32, check out https://iotespresso.com/category/esp32/. Also, you may find this course on ESP32 on Udemy to be quite helpful. Do check it out

Leave a comment

Your email address will not be published. Required fields are marked *