user1810768
user1810768

Reputation: 21

Solving memory leaks using free

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

Answers (2)

Peter Gluck
Peter Gluck

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

Chris Dodd
Chris Dodd

Reputation: 126526

In your free loop, you use head++ which will give you garbage. You want head = head->link

Upvotes: 0

Related Questions