2016-12-04 50 views
0

我有一個鏈接的數據結構,我想要複製並保存原始鏈接。所以我可以編輯原始鏈接列表而不影響複製的鏈接列表。我嘗試了以下方法,並且出現了分段錯誤。在C中使用strdup複製鏈接列表

struct link { 
     char * name; 
     struct link *next; 
    }; 


struct list{ 
     struct link *first; 
     struct link *last; 
    }; 



struct list *list_new(){ 
    struct list *n = calloc(1, sizeof(struct list)); 
    return n; 
}; 




struct list* copyList(struct list*list){ 
    struct list*new = list_new(); 
    struct link *current = list -> first; 
    struct link *newCurrent = new -> first; 
    struct link *p; 
     if(current == NULL) 
     return NULL; 


     newCurrent = malloc(sizeof(struct link)); 
     newCurrent = p; 

     while (current != NULL) { 
     p ->name = strdup((char*)current -> name); 
     p->next = malloc(sizeof(struct link)); 
     p = p->next; 
     current = current->next; 
     } 

     return new; 
    } 
+0

'newCurrent =的malloc(的sizeof(結構鏈接)); newCurrent = p;':分配然後通過uninitialize變量覆蓋。另外'if(current == NULL) return NULL;':發生內存泄漏。 '返回新的;':沒有分配。 – BLUEPIXY

回答

0

我想你想要的東西,如:

struct list *copyList(struct list *list) 
{ 
    struct list *new = list_new(); 
    struct link *current = list->first; 
    struct link *newCurrent = malloc(sizeof(struct link)); 

    if((current == NULL) || (newCurrent == NULL) || (new == NULL)) 
    { 
     if(newCurrent != NULL) 
     { 
      free(newCurrent); 
     } 
     if(new != NULL) 
     { 
      free(new); 
     } 

     return NULL; 
    } 
    else 
    { 
     new->first = newCurrent; 
    } 


    while(current != NULL) 
    { 
     newCurrent->name = strdup((char*)current -> name); 
     current = current->next;   
     if(current != NULL) 
     { 
      newCurrent->next = malloc(sizeof(struct link)); 
      newCurrent = newCurrent->next; 
     } 
     else 
     { 
      newCurrent->next = NULL; 
      new->last = newCurrent; 
     } 
    } 

    return new; 
} 
+0

@ kodper89謝謝,但我正在編譯錯誤新= NULL,錯誤:左值操作數需要作爲賦值 if(current == NULL || newCurrent == NULL || new = NULL) –

+0

@ user3262564現在試試我在new = NULL和缺少免費分號(新當前) – koper89

+0

中有拼寫錯誤。@ kodper89編程接收到的信號SIGSEGV,在list.c中copyList(list = 0x6068b0)處的分段0x00000000004021b4 new-> first = newCurrent; (gdb)p *(new - > first),無法訪問地址0x0處的內存; (gdb)p *(newCurrent) $ 1 = {name = 0x0,next = 0x0}。在這一行似乎有一些問題,它不分配內存空間 –