I am going through a codebase, that uses the FatFS library by Chan and probably developed using the CubeMX code generator. I can see the code given below there. It is also described in STM32 user manual UM1721
A structure is defined as follows:
typedef struct
{
uint8_t is_initialized[_VOLUMES];
Diskio_drvTypeDef *drv[_VOLUMES];
__IO uint8_t nbr;
}Disk_drvTypeDef;
disk
is A global variable defined as:
Disk_drvTypeDef disk = {0};
A function is defined as follows:
uint8_t FATFS_LinkDriver(Diskio_drvTypeDef *drv, char *path)
{
uint8_t ret = 1;
uint8_t DiskNum = 0;
if(disk.nbr <= _VOLUMES)
{
disk.is_initialized[disk.nbr] = 0;
disk.drv[disk.nbr] = drv;
DiskNum = disk.nbr++;
path[0] = DiskNum + '0';
path[1] = ':';
path[2] = '/';
path[3] = 0;
ret = 0;
}
return ret;
}
My question is what happens when the disk.nbr == _VOLUMES
, and I call the FATFS_LinkDriver
function. Won't it try to place drv
into disk.drv[_VOLUMES]
? But the disk.drv
is of size _VOLUMES
. So shouldn't the maximum index be 1 less than that? Am I missing something?
This code invokes undefined behavior in this line:
disk.drv[disk.nbr] = drv;
when disk.nbr == _VOLUMES
.
Is this code from STM32 FATFS User manual (um1721 ) correct?
No, it is not. General remark - there is no guarantee that the code found in the documentation will be correct.