gpt4 book ai didi

c - 释放动态数组中的指针

转载 作者:行者123 更新时间:2023-11-30 16:01:03 25 4
gpt4 key购买 nike

继我之前的问题之后:

Copying a string from a pointer to a string

我现在正在尝试将复制的字符串添加到动态数组中,该数组的大小将根据 SD 卡上的文件数量逐渐增加,并且一旦卡被换出/更改,就会重新创建某种方式。

这段代码第一次运行良好。当SD卡的内容改变后,调用reReadSD()函数并释放fileList。读取 SD 卡的新内容并将新值写入文件列表,但是,在打印文件列表中的名称时,我得到的是符号而不是正确的名称。我认为这是释放 fileList 并重新初始化它的错误,因为同一代码块在系统启动时工作(第一次调用 reReadSD 时),但在第二次调用时则不然。有人能解释一下吗?

void reReadSD()
{
free(fileList);
files_allocated=0;
num_files=0;
reRead_flag=0;


if(f_mount(0, &fatfs ) != FR_OK ){
/* efs initialisation fails*/
}//end f_mount

FRESULT result;
char *path = '/'; //look in root of sd card
result = f_opendir(&directory, path); //open directory
if(result==FR_OK){
for(;;){
result = f_readdir(&directory, &fileInfo); //read directory
if(result==FR_OK){
if(fileInfo.fname[0]==0){break;} //end of dir reached escape for(;;)
if(fileInfo.fname[0]=='.'){continue;} //ignore '.' files
TCHAR* temp;
temp = malloc(strlen(fileInfo.fname)+1);
strcpy(temp, fileInfo.fname);
AddToArray(temp);
}//end read_dir result==fr_ok
}//end for(;;)
}//end open_dir result==fr_ok
}//end reReadSD

和..

void AddToArray (TCHAR* item)
{
u32 delay;
if(num_files == files_allocated)
{

if (files_allocated==0)
files_allocated=5; //initial allocation
else
files_allocated+=5; //more space needed

//reallocate with temp variable
void *_tmp = realloc(fileList, (files_allocated * sizeof(TCHAR*)));

//reallocation error
if (!_tmp)
{
LCD_ErrLog("Couldn't realloc memory!\n");
return;
}

fileList = _tmp;

}//end num_files==files_allocated

fileList[num_files] = item;
num_files++;

}//end AddToArray

与..

TCHAR **fileList;
u32 num_files=0;
u32 files_allocated=0;

最佳答案

就我而言,您在数据段中声明了 fileList 指针。所以它的初始值是NULL。当你重新分配时,它的作用就像malloc一样。但是当你释放它时,它仍然指向某个地方并且重新分配失败。您可能应该设置 fileList = NULL 才能生存。

希望这有帮助。

关于c - 释放动态数组中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7201544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com