【发布时间】:2014-11-16 04:29:39
【问题描述】:
在这段代码中:
Node *CopyList(Node **head) {
Node *current = *head;
Node *NewNode = NULL;
Node *tail = NULL;
while (current != NULL ) {
if (NewNode == NULL) {
NewNode = malloc(sizeof(Node));
NewNode->data = current->data;
NewNode->next = NULL; // routine
tail = NewNode;
} else {
tail->next = malloc(sizeof(Node)); // here
tail = tail->next;
tail->data = current->data;
tail->next = NULL;
}
current = current->next;
}
return(NewNode);
}
为什么我们将tail->next 分配给malloc() 调用的结果?显然,如果我们不这样做,就会发生分段错误。
我们为什么不直接分配tail 而不是tail->next?什么情况下我应该这样分配?
【问题讨论】:
-
这段代码看起来很合理。在第一次迭代中,它分配新列表的头部 (
NewNode),在随后的每次迭代中,它扩展新列表的尾部。你认为这有什么问题?由于tail,不应该有段错误,因为它在使用时不会为NULL。这里唯一的错误是malloc的返回值没有检查为NULL。 -
我不认为这是错误的,只是我没有得到它的方式。
标签: c memory-management linked-list