使用链接列表结构跟踪C程序中可能的内存泄漏

时间:2015-11-18 19:46:05

标签: c struct memory-leaks singly-linked-list

该程序应该读取输入直到0或读取负数。然后使用下面的结构按升序将其放入链表中。

当我通过电子邮件发送测试用例0-3时,我将它们全部通过了。这些输入由随机数组成,如1 2 3 4 5 -1或3493494 2922 -1。

最后一个输入文件是“#### failed test”,它包含一个空白页面,它是输入的txt。所以我的程序自动说“链表是空的”。但是存在内存检查错误。

这个错误是因为阻止了吗?应该“自由(curr);”在printf之后?

  if(head == NULL)
  {
     printf("The list is empty\n");
     return(-1);
  }

我问这个是因为当程序正常运行并执行时它到达最后一行,它释放了curr变量的内存。但是当列表为空时,它立即转到“head == NULL”语句并退出而不释放变量。

我的教授通过电子邮件向我发送了每个输入不同的测试用例:

 #### Passed test 0.
 #### Passed test 1.
 #### Passed test 2.
 #### Passed test 3.
 #### Failed test MemoryCheck. Output of memory checker follows.
 ==23571== 128 (32 direct, 96 indirect) bytes in 2 blocks are definitely        
 lost in loss record 2 of 2
 ==23571== at 0x4A07218: malloc (vg_replace_malloc.c:296)
 ==23571== by 0x40071A: main (in /eecs/dept/course/2015-    
 16/F/2031/submit/lab7/cse13020/q2) 
 ==23571== 

代码:

#include<stdio.h>
#include<stdlib.h>


struct node
{
   int node;
   struct node* next;
};


void insert(struct node** head, struct node* node)
{
    struct node* curr;

    if (*head == NULL || (*head)->node >= node->node)
    {
       node->next = *head;
       *head = node;
    }
    else
    {
       curr = *head;

        while (curr->next!= NULL && curr->next->node < node->node)
           curr = curr->next;

        node->next = curr->next;
        curr->next = node;
    }
}


int main()
{

   struct node *head = NULL;
   struct node *curr;

   int n;

   while(1)
   {

      scanf("%d", &n);

      if(n <= 0) 
        break;

      curr = (struct node*) malloc(sizeof(struct node));
      curr->node  = n;
      curr->next =  NULL;

      insert(&head, curr); 
   }

  if(head == NULL)
  {
     printf("The list is empty\n");
     return(-1);
  }

  printf("The linked list is:\n");

  while(1)
  {
     if(head == NULL) {
       printf("NULL\n");
       break;
     }
     printf("%d-->", head->node);
     head = head->next;
  }


  free(curr);  
}

1 个答案:

答案 0 :(得分:1)

你需要在最后一个while循环中释放head节点:

while(1)
{
  if(head == NULL) {
    printf("NULL\n");
    break;
  }
  printf("%d-->", head->node);
  void *tmp = head;
  head = head->next;
  free(tmp);
}

并删除free(curr);

您还应该检查scanf是否成功,或者将n设置为某个负值。