2

我正在尝试消除以下程序中的内存泄漏

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;
}

然而,当我运行 valgrind 时,它会因内存泄漏而发疯,这里知道我做错了什么吗?

4

2 回答 2

1

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.

于 2012-11-08T22:59:37.900 回答
0

在你的free循环中,你使用head++which 会给你垃圾。你要head = head->link

于 2012-11-08T23:09:27.940 回答