内存分配释放(Memory Allocation Freeing)

编程入门 行业动态 更新时间:2024-10-20 05:25:01
内存分配释放(Memory Allocation Freeing)

我正在编写链接列表,并在删除节点时尝试释放内存分配。 但是,经过几个小时的尝试,我似乎无法获得干净的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.

更多推荐

本文发布于:2023-07-05 06:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配   内存   Memory   Allocation   Freeing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!