2014-02-10 44 views
0

我有一個結構的下面的代碼定義一個鏈表編寫釋放從鏈接列表中創建存儲功能

struct list { 
    struct student s; 
    struct list *next; 
}; 

我的學生結構被定義爲以下

struct student{ 
    unsigned short year; 
    unsigned short grade; 
    unsigned char *details; 
}; 
的節點

因此,假設我的程序創建了學生的鏈表,我想寫一個函數來釋放我所做的每個malloc調用。

在我的程序中,我每次初始化*詳細信息時都做一個malloc調用,並且每次我爲該列表創建一個節點。

如果這會有所幫助,這是我的功能,創建一個節點:

struct list *create_node(struct student *p) { 
    struct list *node = malloc(sizeof(struct list)); 
    node->p = *p; 
    node->next = NULL; 
    return node; 
} 

我想寫fress所有的一切使用malloc爲舉行列表的存儲功能。

這是我嘗試

void free_list(struct list *node){ 

    // free this first node 
    free(node->p.details); 
    while (node->next != NULL){ 
     // become the next node and free 
     node = node->next; 
     free(node->p.details); 
    } 
+4

你是否對代碼有問題你寫的嗎?如果是這樣,你可能會描述你遇到的問題。 – mah

+0

你如何創建你的學生對象,並釋放他們自己使用的內存? –

+0

有一個錯字。在'node-> p'中,沒有叫'p'的成員。 – Jeyaram

回答

2

您的免費功能,可就是這樣

void free_list(struct list *node){ 

struct list *temp = NULL; 

// free this first node 
//free(node->p.details); 
while (node != NULL){ 
    temp = node; 
    // become the next node and free 
    node = node->next; 
    free(temp->p.details); 
    temp->p.details = NULL; 
free(temp); 
}