释放动态数组中的指针

时间:2011-08-26 07:48:14

标签: c arrays dynamic free

继我之前的一个问题之后:

Copying a string from a pointer to a string

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

此代码第一次正常工作。更改SD卡的内容后,将调用reReadSD()函数并释放fileList。读取SD卡的新内容并将新值写入fileList,但是,在从fileList打印出名称时,我得到符号而不是正确的名称。我认为这是释放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;

2 个答案:

答案 0 :(得分:1)

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

希望这有帮助。

答案 1 :(得分:0)

我在这段代码中看不到任何明显的错误,除非free(fileList)调用标准库free函数,你只释放由指针数组分配的内存,而不是个人其元素指向的字符串,因此您有内存泄漏。相反,您需要迭代数组并依次释放每个元素,然后释放数组本身。但这并不能解决你的直接问题。

我能推荐的最好的方法是调试代码,或者在关键位置调试打印输出,以跟踪程序中实际发生的事情。

相关问题