carlk3/no-OS-FatFS-SD-SDIO-SPI-RPi-Pico

Filepointer gets corrupt in f_wrirte and program crashes

Closed this issue · 2 comments

After calling f_write the filepointer gets corrupt and crashes when trying to close the file.
Here is an example :

const char *SerNumFName = "SerNum.txt";

pico_unique_board_id_t board_id;
pico_get_unique_board_id(&board_id);
uint8_t SecretKey[] = {54,78,45,32,222,87,48,32};
uint8_t SerialNumber[16];
memset(SerialNumber, 0, 8);
int n;
int i=0;
for(n=7; n>=0; n--)
{
uint8_t el = board_id.id[n];
uint8_t new_el = (el ^ SecretKey[n]) ^ n;
SerialNumber[i] = new_el;
i++;
}
FIL SN_fil;
char tmp[64];
memset(tmp, 0, 32);
sprintf(tmp, "%02X%02X%02X%02X%02X%02X%02X%02X", SerialNumber[0], SerialNumber[1],SerialNumber[2],SerialNumber[3],SerialNumber[4],SerialNumber[5],SerialNumber[6],SerialNumber[7]);
tmp[16]=0;
FRESULT SN_fr;

if(f_exists((char *)SerNumFName))
{
    f_unlink(SerNumFName);
}
SN_fr = f_open(&SN_fil, SerNumFName, FA_CREATE_NEW | FA_READ | FA_WRITE);
//SN_fr = f_open(&SN_fil, SerNumFName, FA_CREATE_NEW | FA_WRITE);
if (SN_fr != FR_OK) 
{
    printf("Failed to open to file %s\r\n", SerNumFName);
    return false;
}        
UINT BytesWritten = 0;
char ttt[64]; memset(ttt, 0, 64);
SN_fr = f_write(&SN_fil, tmp, 16, &BytesWritten);
if(SN_fr!=FR_OK || BytesWritten!=16)
{
    printf("Failed to write Serial Number to file %s\r\n", SerNumFName);
}        
f_close(&SN_fil);
carlk3 commented

What is f_exists?

carlk3 commented

I had to comment out a couple of lines, but this runs fine here:
my_test.zip