fix(fatfs): fix a memory leak bug when FF_USE_DYN_BUFFER was enabled

This commit is contained in:
LiPeng
2026-04-21 11:54:39 +08:00
parent 9a41bbaf7d
commit a8b5b8d582
7 changed files with 136 additions and 49 deletions
+15 -12
View File
@@ -3513,8 +3513,10 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */
if (SS(fs) > FF_MAX_SS || SS(fs) < FF_MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
#endif
#if FF_USE_DYN_BUFFER
fs->win = ff_memalloc(SS(fs)); /* Allocate memory for sector buffer */
if (!fs->win) return FR_NOT_ENOUGH_CORE;
if (!fs->win) {
fs->win = ff_memalloc(SS(fs)); /* Allocate memory for sector buffer */
if (!fs->win) return FR_NOT_ENOUGH_CORE;
}
#endif
/* Find an FAT volume on the hosting drive */
@@ -3768,8 +3770,10 @@ FRESULT f_mount (
ff_mutex_delete(vol);
#endif
#if FF_USE_DYN_BUFFER
if (cfs->fs_type) /* Check if the buffer was ever allocated */
if (cfs->win) { /* Check if the buffer was ever allocated */
ff_memfree(cfs->win); /* Deallocate buffer allocated for the filesystem object */
cfs->win = NULL;
}
#endif
cfs->fs_type = 0; /* Invalidate the filesystem object to be unregistered */
}
@@ -3955,18 +3959,15 @@ FRESULT f_open (
#if !FF_FS_READONLY
#if !FF_FS_TINY
#if FF_USE_DYN_BUFFER
fp->buf = NULL;
if (res == FR_OK) {
if (!fp->buf) {
fp->buf = ff_memalloc(SS(fs));
if (!fp->buf) {
res = FR_NOT_ENOUGH_CORE; /* Not enough memory */
goto fail;
}
memset(fp->buf, 0, SS(fs)); /* Clear sector buffer */
}
#else
memset(fp->buf, 0, SS(fs)); /* Clear sector buffer */
#endif
memset(fp->buf, 0, SS(fs)); /* Clear sector buffer */
#endif
if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
DWORD bcs, clst;
@@ -4350,15 +4351,17 @@ FRESULT f_close (
#else
fp->obj.fs = 0; /* Invalidate file object */
#endif
#if !FF_FS_TINY && FF_USE_DYN_BUFFER
ff_memfree(fp->buf);
fp->buf = NULL;
#endif
#if FF_FS_REENTRANT
unlock_volume(fs, FR_OK); /* Unlock volume */
#endif
}
}
#if !FF_FS_TINY && FF_USE_DYN_BUFFER
if (fp->buf) {
ff_memfree(fp->buf);
fp->buf = NULL;
}
#endif
return res;
}