2011-07-19 132 views
1

我有一個結構,我用來建立一個鏈表如下;分配最近釋放的內存

struct my_struct{ 
    char a[16]; 
    struct my_struct *next; 
} 

我通過下面的函數釋放鏈表;

void free_my_list(struct my_struct* recv) { 

    if (recv->next != NULL) 
     free_my_list(recv->next); 

    free(recv); 
    recv = NULL; 
} 

在我的計劃,我使用結構_my_list一遍又一遍,但自由如下每一次的malloc它:

struct my_struct *_my_list; 

free_my_list(_my_list); 
_my_list = (my_list *) malloc(sizeof(my_list)); 
_my_list->next = NULL; 

我每次填充列表,我打印字符數組,然後復位_my_struct由上面的代碼。 以上代碼在Ubuntu pc上工作正常,但在Cent OS上正確打印第一個列表(在第一個malloc _my_struct之後)後,列表被打印爲損壞的數據。

當我在整個程序執行過程中沒有釋放和malloc內存時,它在Cent OS中也可以正常工作,但我應該在printf()調用之間重置列表_my_list

_my_list通過以下函數進行填充和打印;

/*prints every item in my_list*/ 
void print_my_list(struct my_struct *recv, FILE *fd) { 

    my_list *tmp; 
    tmp = recv; 

    while (tmp != NULL) { 
     if (fwrite(tmp->a, 1, strlen(tmp->a), fd) == -1) { 
       pritnf("error\n"); 
     } 
     tmp = tmp->next; 
    } 
} 

/*Add 'a' string to _my_list*/ 
void add_recv_to_list(struct my_struct **recv_list, char *recv) { 

struct my_struct *tmp; 
tmp = *recv_list; 

if (*recv_list == NULL) { 
    *recv_list = (struct my_struct *) malloc(sizeof(struct my_struct)); 
    tmp = *recv_list; 

} else { 

    while ((tmp->next) != NULL) { 
     tmp = tmp->next; 
    } 
    tmp->next = (struct my_struct *) malloc(sizeof(struct my_struct)); 
    tmp = tmp->next; 

} 
strncpy(tmp->a, recv, MAX_NAME_LEN); 
tmp->next = NULL; 
} 

什麼是可以的原因,任何想法?

+0

我認爲你需要證明填充列表的代碼而且,'my_list'一個'結構my_struct' –

+0

發佈你的?完整的示例您缺少一個typedef或一些結構 –

+1

如何填充列表。在自由列表函數中recv = NULL什麼也不做。您最好傳遞my_struct **,以便從列表中清除列表指針該例程。 –

回答

1

我認爲你的問題可能從這裏開始:

struct my_struct *_my_list; 

free_my_list(_my_list); 
_my_list = (my_list *) malloc(sizeof(my_list)); 
_my_list->next = NULL; 

當初始化STRUC:struct my_struct *_my_list;你不給它分配任何值,所以它擁有的任何垃圾數據在內存事先。當你在free_my_list中登錄free()時,行爲是不確定的(你正在釋放一些你永遠不會得到的東西 - 所以結果很可能是後來某件事或其他東西的損壞)嘗試將你的聲明更改爲:struct my_struct *_my_list = NULL;初始化指針爲NULL,反正),並改變你的free_my_list功能:

void free_my_list(struct my_struct* recv) { 
    if (recv == NULL) 
     return; 

    if (recv->next != NULL) 
     free_my_list(recv->next); 

    free(recv); 
    recv = NULL; 
}