内存分配释放

发布于 2024-12-10 11:15:18 字数 660 浏览 5 评论 0原文

我目前正在编写一个链表,并尝试在删除节点时释放内存分配。然而,经过几个小时的尝试,我似乎无法获得干净的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浪荡不羁 2024-12-17 11:15:18

哇哦,你的 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.

怪我闹别瞎闹 2024-12-17 11:15:18
node = malloc(sizeof(*node));

node指向的事物分配空间。

不要强制转换 malloc 的返回值。这样做可以掩盖 #include 的失败。

node = malloc(sizeof(*node));

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>.

孤蝉 2024-12-17 11:15:18

看来是对的。还是其他地方有漏水的情况?或者您是否将元素本身作为传入的参数释放?

It seems correct. Or are there some leaks in the other places? Or do you free the element itself as the parameter passed in ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文