Reputation: 21
I am trying to eliminate memory leaks in my following program
int main (int argc, char **argv) {
node_ref head = NULL;
for (int argi = 0; argi < 5; ++argi) {
node_ref node = malloc (sizeof (struct node));
assert (node != NULL);
node->word = argv[argi];
node->link = head;
head = node;
}
for (node_ref curr = head; curr->link != NULL; curr = curr->link) {
printf ("%p->node {word=%p->[%s], link=%p}\n",
curr, curr->word, curr->word, curr->link);
}
while(head != NULL){
struct node* temp;
temp = head;
head++;
free(temp);
}
return 9;
}
Yet when I run valgrind it goes crazy with memory leaks, any idea here on what I'm doing wrong?
Upvotes: 2
Views: 97
Reputation: 8236
You are allocating memory inside the loop which is resulting in multiple memory areas. It looks like you should be calling malloc() before your loop instead.
EDIT:
After looking at this again, I think the second loop that frees the memory is incorrect. You are incrementing with head++;
rather than setting head = temp->link;
It is incorrect to assume that malloc
will give you contiguous memory segments.
Upvotes: 1
Reputation: 126526
In your free
loop, you use head++
which will give you garbage. You want head = head->link
Upvotes: 0