2016-12-04 5 views
0

私は元のリンクをコピーして保存するリンク先のデータ構造を持っています。だから私はコピーされたリンクリストに影響を与えずに元のリンクリストを編集することができます。私は次の方法を試して、私はセグメンテーションフォールトを持っています。strdupを使用してCでリンクリストをコピー

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; ':変数を初期化しないで上書きします。また、 'if(current == NULL) はNULLを返します;':はメモリリークを起こします。 'return new;':割り当てられていません。 – 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、エラーでエラーをコンパイルしています:左辺のオペランドには左辺のオペランドが必要です(現在== NULL || newCurrent == NULL || new = NULL) –

+0

@ user3262564 (newCurrent) – koper89

+0

の@codper89プログラム受信シグナルSIGSEGV、セグメンテーション0x00000000004021b4のコピーリスト(list = 0x6068b0)(list.c) new-> first = newCurrent; (gdb)p *(new - > first)、アドレス0x0のメモリにアクセスできません。 (gdb)p *(newCurrent) $ 1 = {名前= 0x0、次= 0x0}。この行で問題があるようですが、メモリスペースを割り当てません。 –

関連する問題