簡體   English   中英

釋放動態數組中的指針

[英]Freeing pointers in a dynamic array

在上一個問題之后,我在這里:

將字符串從指針復制到字符串

我現在正嘗試將復制的字符串添加到動態數組中,該數組的大小將根據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;

就我而言,您在數據段中聲明了FileList指針。 因此它的初始值為NULL。 當您重新分配它時,它就像malloc一樣。 但是當您釋放它時,它仍然指向某個位置,並且重新分配失敗。 您可能應該設置fileList = NULL才能生存。

希望這可以幫助。

我看不到這段代碼中有任何明顯的錯誤,除了free(fileList)調用標准庫的free函數之外,您只釋放了指針數組分配的內存,而不釋放其元素指向的單個字符串,因此您有內存泄漏。 相反,您需要遍歷數組並依次釋放每個元素,然后再釋放數組本身。 但這不能解決您的直接問題。

我推薦的最佳方法是調試代碼,或在關鍵位置放置調試打印輸出,以跟蹤程序內部實際發生的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM