mbed M0 restart by repeating fopen and fclose

17 Apr 2012

We are discussing about mbed-M0 problem in Japanese-forum: http://mbed.org/forum/ja/topic/3431/ )

In that topic, Mr.Ida reported the mbed-M0 is forced to be restarted when file open and close repeated 146 times.
That is confirmed on my yellow mbed too. This is not happen on M3.

Please find a code sample below. This code prints the repeated count with return value of fopen.

I found a strange behavior: file pointer increment can be seen at each fopen call. In a very simple program like this code, I guess the library may try to get same memory space for the FILE structure if the file is closed properly. (I tried to run same code on M3 and it returns same value every time and continues to run without restart.)

So I guess something strange is happening inside of library.

Import programM0_restert_by_file_open_close_repeat

sample of problem: M0 restarted by file-open-close repeat 146 times

main.cpp

#include "mbed.h"

LocalFileSystem SeqFile("Local");

int main() {
    FILE    *fp;
    int     i   = 1;

    printf( "\r\nSTART\r\n" );
    wait( 0.1 );

    while ( 1 ) {
        fp = fopen( "/Local/TEST.csv", "r" );
        if (!fp) {
            printf( "error %d\r\n", i );
            exit( 1 );
        } else {
            printf( "%d (%p)\r\n", i, fp );
            fclose( fp );
        }
        wait( 0.1 );
        i++;
    }
}

sample_of_M0_output

START
1 (100001a8)
2 (100001c0)
3 (100001d8)
....
...
145 (10000f28)
146 (10000f40)�
START
1 (100001a8)
2 (100001c0)

sample_of_M3_output

START
1 (100002e0)
2 (100002e0)
3 (100002e0)
....
...
07 Oct 2013

Hi Okano-san,

I've got a reply from support team of ARM compiler and this is an defect of the fclose() function in micro library. A microlib version of the fclose() function doesn't call free() which is a bug.

Following code workaround this issue.

#include "mbed.h"
 
LocalFileSystem SeqFile("Local");
 
int main() {
    FILE    *fp;
    int     i   = 1;
 
    printf( "\r\nSTART\r\n" );
    wait( 0.1 );
 
    while ( 1 ) {
        fp = fopen( "/Local/TEST.csv", "r" );
        if (!fp) {
            printf( "error %d\r\n", i );
            exit( 1 );
        } else {
            printf( "%d (%p)\r\n", i, fp );
            fclose( fp );
#if defined(__MICROLIB) && defined(__ARMCC_VERSION) // with microlib and ARM compiler
            free(fp);
#endif
        }
        wait( 0.1 );
        i++;
    }
}

I will let you know when this defect will be fixed.

07 Oct 2013

(message has been erased because it has been posted from wrong account)

07 Oct 2013

Hi Watarai-san,

Great!
Now the problem and workaround are clear.

Thank you very much! Looking forward to getting fixed version micro-lib in future.