内存分配释放
我目前正在编写一个链表,并尝试在删除节点时释放内存分配。然而,经过几个小时的尝试,我似乎无法获得干净的 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 函数中,我想取出列表的头部并使头部的下一个节点成为新的头部。我想释放分配给 head 的内存。
感谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哇哦,你的
malloc
不正确。你有:你需要的是:
在你的原始代码中,你只为指针分配了足够的空间。但是您正在尝试分配一个 Node 对象。
Woah, your
malloc
isn't correct. You have:What you need is:
In your original code, you are only allocating enough for a pointer. But you are trying allocate a
Node
object.为
node
指向的事物分配空间。不要强制转换
malloc
的返回值。这样做可以掩盖#include
的失败。Allocate space for the thing pointed to by
node
.Don't cast the return value of
malloc
. Doing so can mask the failure to#include <stdlib.h>
.看来是对的。还是其他地方有漏水的情况?或者您是否将元素本身作为传入的参数释放?
It seems correct. Or are there some leaks in the other places? Or do you free the element itself as the parameter passed in ?