Reputation: 1839
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
Upvotes: 1
Views: 156
Reputation: 118118
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>
.
Upvotes: 1
Reputation: 12896
It seems correct. Or are there some leaks in the other places? Or do you free the element itself as the parameter passed in ?
Upvotes: 0
Reputation: 471209
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.
Upvotes: 3