編輯*
我正在學習結構和指標,我正在處理的部分任務要求我釋放 malloc 的空間以用于結構指標。指標作為函式內部的引數傳遞,我想知道是否可以釋放函式內部的空間?指標在主檔案中宣告,所有的函式代碼都在一個單獨的檔案中。下面是我的代碼,當它經過測驗時,Valgrind 會在 main 中宣告 dict 的那一行說記憶體泄漏。任何有關如何處理此問題的提示將不勝感激。
生成結構體指標的代碼:
typedef struct dict_list {
char* key;
char* val;
struct dict_list* next;
} dict_list_t;
typedef struct dict {
dict_list_t* head;
size_t size;
} dict_t;
dict_t* dict_create () {
dict_t *ret = (dict_t *) malloc(sizeof(dict_t));
ret -> head = NULL;
ret -> size = 0;
return ret;
}
然后在主檔案中呼叫它:
int main (int argc, char** argv) {
dict_t* dict = dict_create ();
被呼叫以洗掉整個串列的函式
void dict_destroy (dict_t* dict) {
dict_list_t* el = dict->head;
dict_list_t* next_val;
while(el){
next_val = el->next;
dict_del(dict,el->key); //removes the key/value pair in dict if a matching key is found
el = next_val;
}
free(el);
free(dict->head);
free (dict);
}
這是我從 Valgrind 得到的錯誤資訊
HEAP SUMMARY:
==1801801== 16 bytes in 1 blocks are still reachable in loss record 1 of 2
==1801801== at 0x4C34F0B: malloc (vg_replace_malloc.c:307)
==1801801== by 0x400A77: dict_create (dict.c:18)
==1801801== by 0x400DEC: main (main.c:11)
uj5u.com熱心網友回復:
一個函式指向free
一個malloc
在其他函式中被編輯的指標是完全沒問題的。但是,撰寫檔案注釋讓呼叫函式的人知道指標正在被釋放是非常重要的。我們不能在 C 中讓這些東西碰運氣。
在您當前的編輯中,我們看到dict_t
有一個指標欄位head
,但我們不知道是否dict_clear
釋放了該指標。那可能是你的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/318813.html
下一篇:如何在C中找到鍵/值字典的大小