@@ -86,9 +86,6 @@ uint32_t mbed_heap_size = 0;
8686 * (or rather index+3, as filehandles 0-2 are stdin/out/err).
8787 */
8888static FileLike *filehandles[OPEN_MAX];
89- #if MBED_CONF_FILESYSTEM_PRESENT
90- static File fileobjects[OPEN_MAX];
91- #endif
9289static SingletonPtr<PlatformMutex> filehandle_mutex;
9390
9491namespace mbed {
@@ -162,6 +159,27 @@ extern "C" WEAK void mbed_sdk_init(void);
162159extern " C" WEAK void mbed_sdk_init (void ) {
163160}
164161
162+ #if MBED_CONF_FILESYSTEM_PRESENT
163+ // Internally used file objects with managed memory on close
164+ class ManagedFile : public File {
165+ public:
166+ virtual int close () {
167+ int err = File::close ();
168+ delete this ;
169+ return err;
170+ }
171+ };
172+
173+ class ManagedDir : public Dir {
174+ public:
175+ virtual int close () {
176+ int err = Dir::close ();
177+ delete this ;
178+ return err;
179+ }
180+ };
181+ #endif
182+
165183/* @brief standard c library fopen() retargeting function.
166184 *
167185 * This function is invoked by the standard c library retargeting to handle fopen()
@@ -251,11 +269,13 @@ extern "C" FILEHANDLE PREFIX(_open)(const char* name, int openmode) {
251269 return -1 ;
252270 }
253271 int posix_mode = openmode_to_posix (openmode);
254- int err = fileobjects[fh_i].open (fs, path.fileName (), posix_mode);
272+ File *file = new ManagedFile;
273+ int err = file->open (fs, path.fileName (), posix_mode);
255274 if (err < 0 ) {
256275 errno = -err;
276+ delete file;
257277 } else {
258- res = &fileobjects[fh_i] ;
278+ res = file ;
259279 }
260280#endif
261281 }
@@ -536,7 +556,7 @@ extern "C" DIR *opendir(const char *path) {
536556 FileSystem* fs = fp.fileSystem ();
537557 if (fs == NULL ) return NULL ;
538558
539- Dir *dir = new Dir ;
559+ Dir *dir = new ManagedDir ;
540560 int err = dir->open (fs, fp.fileName ());
541561 if (err < 0 ) {
542562 errno = -err;
@@ -572,7 +592,6 @@ extern "C" struct dirent *readdir(DIR *dir) {
572592extern " C" int closedir (DIR *dir) {
573593#if MBED_CONF_FILESYSTEM_PRESENT
574594 int err = dir->close ();
575- delete dir;
576595 if (err < 0 ) {
577596 errno = -err;
578597 return -1 ;
0 commit comments