FATFS memory leak when calling fopen

Wootsies
Posts: 6
Joined: Fri Sep 18, 2020 7:32 pm

FATFS memory leak when calling fopen

Postby Wootsies » Mon Nov 30, 2020 11:53 am

Hi everyone, I have implemented a FATFS for a partition on my flash memory and have been observing a strange behavior after awhile where I can no longer create a file using the command fopen(filepath, "wb"). The call to fopen returns null and the error code is 2.
Calling perror("error") returns: Error: No such file or directory. Then when I tried to get the current memory from f_getfree, I realised that my free sectors have been reduced down to 0. In my code typically i call fopen with the mode set to wb and each time before I write to the file, I will call the unlink method.

It is strange because I cannot seem to isolate the scenario where this will happen however it will trigger maybe after several days or weeks of developing on the ESP32. Additionally when I reflash my ESP32 my original assumptions were that it would clear/format the FATfs partition but it seems that given this is happening, it seems my assumption is incorrect.

During my testing when I run my code, the data that I am writing to the FATFS is typically always the same length and I have not touched this part of the code at all for quite awhile and it will trigger this issue without much warning after flashing/working on the code for a while.

Has anyone encountered this before or is able to give some input to identify where the issue could be coming from?


Note: Flash encryption is not enabled and I am writing to a partition on my external flash
An extract of the code I use to add the file:

Code: Select all

    
    // Remove file before adding
    unlink(filepath);

    // Open file to write
    FILE *f = fopen(filepath, "wb");
    if (f == NULL)
    {
        ESP_LOGE(TAG, "Failed to open file for writing. Error code: %d", errno);
        perror("Error");
        return ESP_FAIL;
    }
    else
    {
        // Write data to the file here
        if (fprintf(f, "%s", inBuffer) == EOF)
        {
            ESP_LOGE(TAG, "File Write Error, Memory Might be full");
            fclose(f);
            return ESP_FAIL;
        }
    }

    // Remember to close the file
    fclose(f);

How I mount my partition

Code: Select all

    
    const esp_vfs_fat_mount_config_t mount_config = {
        .max_files = 4,
        .format_if_mount_failed = true,
        .allocation_unit_size = CONFIG_WL_SECTOR_SIZE};

    esp_err_t err = esp_vfs_fat_spiflash_mount(ROOT, NAME, &mount_config, &s_wl_handle_FileStorage);
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
        return ESP_FAIL;
    }

Who is online

Users browsing this forum: Bing [Bot] and 118 guests