私は元のリンクをコピーして保存するリンク先のデータ構造を持っています。だから私はコピーされたリンクリストに影響を与えずに元のリンクリストを編集することができます。私は次の方法を試して、私はセグメンテーションフォールトを持っています。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;
}
'newCurrent = malloc関数(はsizeof(構造体のリンク)); newCurrent = p; ':変数を初期化しないで上書きします。また、 'if(current == NULL) はNULLを返します;':はメモリリークを起こします。 'return new;':割り当てられていません。 – BLUEPIXY