【发布时间】:2018-09-29 07:33:53
【问题描述】:
我试图迭代地为链表释放内存。该列表有一个看起来像这样的结构,在这个链表中,如果它在这个列表中,我不会添加一个 url。
struct Node {
char *url;
struct Node *next;
};
处理完这个链表后,我尝试释放它,但出现分段错误,我仍在学习c,除了如何调试此类错误之外,我没有太多线索直接搜索相关主题。引用了一些 SO this one、this one 和 this one,仍然无法确定它在哪里崩溃。
这是我的代码。如果您认为我在此实现中遗漏了什么,请随意添加 cmets。
void url_push(struct Node *head, const char *url, size_t url_size) {
struct Node *new_node = (struct Node *) malloc(sizeof(struct Node));
new_node->url = malloc(url_size);
new_node->next = NULL;
for (int i = 0; i < url_size; i++)
*(new_node->url + i) = *(url + i);
struct Node *current = head;
while(1) {
if (strcmp(current->url, new_node->url) == 0) {
printf("Seen page %s!!!!!\n", new_node->url);
free(new_node);
break;
} else if (current->next == NULL) {
current->next = new_node;
break;
} else {
current = current->next;
}
}
}
int main() {
struct Node *head = (struct Node*)malloc(sizeof(struct Node));
head->url = "/";
head->next = NULL;
char *url = "www.google.com";
url_push(head, url, strlen(url));
url = "www.yahoo.com";
url_push(head, url, strlen(url));
url = "www.google.com";
url_push(head, url, strlen(url));
url = "www.wsj.com";
url_push(head, url, strlen(url));
struct Node *current = NULL;
while ((current = head) != NULL) {
printf("url: %s\n", head->url);
head = head->next;
free(current->url);
free(current);
}
}
已编辑:
为了减少混淆,我修改了结构。使用strcmp的目的是避免添加已经看到的url。
【问题讨论】:
-
你需要一个
remove()方法来实现删除列表中单个节点的逻辑。这必须注意将前一个节点重新连接到列表中的下一个节点。 -
回答你的问题有太多错误。 invalid、redirect 和 page_size 变量是如何设置的?如果你从不移动它,当前指针是什么?头不应该移动,因为它是列表的开始。既然可以结束程序,为什么还要释放列表?
-
您编辑了结构,但现在您的代码无法编译。如果您提供的代码与您正在使用的代码不同(您通常应该这样做),请确保它重现了相同的问题。
-
here,看看一个好的实现示例 ;) 就像 linus 说“不要说话,给我看代码”
标签: c pointers linked-list