ArduinoJson: There is a memory leak either in this library or in ESP32 LittleFS

Environment
Here is the environment that I’m using’:

  • Microconroller: [ESP32-Wrover-E]
  • Core/runtime: [Arduino (2.0.17) as an IDF(4.4.7) component]
  • IDE: [PlatformIO]

Reproduction
Here is a small snippet that demonstrate the problem.

int read(const char* path, JsonDocument& doc){
    File file = userFS.open(path);
    if(!file){
        #if DB_DEBUG
            logger.write("[FileSystem] - (getJson) File not found: %s\n",path);
        #endif
        return -1;
    }
    DeserializationError error = deserializeJson(doc, file);
    file.close();
    if( error == DeserializationError::Ok ){
        #if DB_DEBUG
            logger.write("[FileSystem] - (getJson) Message read from file: %s\n",path);
        #endif
        return measureJson(doc);
    }
    return -1;
}

Program output
If relevant, include the program output.

Expected output:

No memory leak should happen

Actual output:

Memory leak.

(0) Free block 110592

[HwConfig] - Loaded 47612 bytes

(1) Free block 55296

(2) Free block 55296

My program never recovers from this and continues with free block of 55296 bytes. I’m measuring every min and it never recovers.

This is how I’m using the function


void printFreeBlockMem(int num){
    printf(
        "(%d) Free block %d\n",
        num,
        heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)
    );
}

std::vector<Module> modules;

void load(){
  printFreeBlockMem(0); // Memory is OK

  JsonDocument doc;
  int size = read(HW_CONFIG_PATH, doc);
  if (size == -1) { return; )
  
  printf("[HwConfig] - Loaded %d bytes\n", size); // Read x bytes OK
  // Memory is NOT OK here but it's okay since the JsonDocument is still in scope
  // I would say that, but I have set malloc to allocate from External RAM and since
  // ArduinoJson 7 uses malloc() it should not be the case
  printFreeBlockMem(1);
  
  // Push modules into a vector
  for (JsonPair kv : doc.as<JsonObject>()) {
      JsonObject moduleObj = kv.value().as<JsonObject>();
      modules.push_back(Module(moduleObj));
  }
  modules.shrink_to_fit();
  printFreeBlockMem(2);
}

Since ArduinoJson 7 uses dynamic memory and I have setup malloc use external ram in my IDF config, I expect it to not cause any memory decrease from internal ram, but it does.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 23 (6 by maintainers)

Most upvoted comments

I have 100k free contignous heap and 180k free heap with Arduino_JSON. If I use ArduinoJson V7 I have 40k free contignous heap and 90k free heap

So, ArduinoJson consumes twice as much heap as Arduino_JSON in this situation, which is really bad. I expected to make huge memory optimizations in ArduinoJson 7.1, but my plans were disrupted by #2078. ArduinoJson 7.1 will instead be an all-MessagePack release, and memory optimizations are postponed to 7.2