我有一個鏈接的數據結構,我想要複製並保存原始鏈接。所以我可以編輯原始鏈接列表而不影響複製的鏈接列表。我嘗試了以下方法,並且出現了分段錯誤。在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;
}
'newCurrent =的malloc(的sizeof(結構鏈接)); newCurrent = p;':分配然後通過uninitialize變量覆蓋。另外'if(current == NULL) return NULL;':發生內存泄漏。 '返回新的;':沒有分配。 – BLUEPIXY