pointer is freed but valgrind says it isn't
Вопрос
I freed a pointer that I made, but Valgrind still reports that I've lost bytes, so I'm not really sure how to approach it.
The code in question Is:
listNode* temp = (listNode*)malloc(sizeof(listNode));
node = list->head;
while (node != NULL)
{
temp = node->next;
free(node->entry);
free(node);
node = temp;
}
free(temp);
With the valgrind output:
16 bytes in 1 blocks are definitely lost in loss record 13 of 21
==2137== at 0xB823: malloc (vg_replace_malloc.c:266)
==2137== by 0x100001B1E: freeList (main.c:110)
==2137== by 0x100001CB5: main (main.c:157)
Решение
You don't free
the memory allocated with malloc
in the code given, unless node == NULL
. You allocate a block of memory, assign it to temp
, then go on in the loop to reassign to temp
other addresses, losing the memory that you've allocated with malloc
.
It doesn't look like you need the malloc
at all: you're just using temp
as a temporary pointer: why do you need to allocate memory for it?
Другие советы
It looks like you want to walk the list of nodes freeing up the various links as you go. It appears that the listNode struct contains two members, entry that has a pointer to the node information and next which points to the next node in the list. Finally you have the listNode itself which also needs to be freed.
Assuming that the end of the list is indicated by next being NULL, the approach I would take would be as follows:
listNode *nodeCur, *nodeNext ;
nodeCur= list->head;
while (nodeCur)
{
nodeNext = nodeCur->next;
free(nodeCur->entry);
free(nodeCur);
nodeCur = nodeNext;
}
The next question is what is the variable list. Does it also need to be freed as a part of this removal of the list?