我正在编写链接列表,并在删除节点时尝试释放内存分配。 但是,经过几个小时的尝试,我似乎无法获得干净的valgrind输出。
void * pop(struct List *list) { if(list->head == 0){ return 0; } struct Node * tempNode = list->head->next; free(list->head); list->head = tempNode; ... }我正在分配空间说:
addNode(struct List *list, void *element){ struct Node *node; node = (struct Node *)malloc(sizeof(node)); .... }基本上在pop函数中我想要取出列表的头部并使头部的下一个节点成为新的头部。 我想释放给予头部的记忆。
谢谢你的帮助
I'm currently writing a linked list and trying to free up memory allocations when I delete a node. However, after hours of trying to do this, I can't seem to get a clean valgrind output.
void * pop(struct List *list) { if(list->head == 0){ return 0; } struct Node * tempNode = list->head->next; free(list->head); list->head = tempNode; ... }I'm allocating the space by saying:
addNode(struct List *list, void *element){ struct Node *node; node = (struct Node *)malloc(sizeof(node)); .... }Basically in the pop function I want to take out the head of the list and make the head's next node the new head. I want to deallocate the memory that was given to head.
Thanks for any help
最满意答案
哇,你的malloc不正确。 你有:
(struct Node *)malloc(sizeof(node));你需要的是:
(struct Node *)malloc(sizeof(struct Node));在原始代码中,您只为指针分配足够的内容。 但是您正在尝试分配Node对象。
Woah, your malloc isn't correct. You have:
(struct Node *)malloc(sizeof(node));What you need is:
(struct Node *)malloc(sizeof(struct Node));In your original code, you are only allocating enough for a pointer. But you are trying allocate a Node object.
更多推荐
发布评论