【问题标题】:Tracking Possible Memory Leak in C program using Linked List Struct使用链表结构跟踪 C 程序中可能的内存泄漏
【发布时间】:2016-02-20 17:11:33
【问题描述】:

该程序应该读取输入,直到读取到 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);  
}

【问题讨论】:

  • 当您最终打印列表时,while(1) 应该是 while(head)。你已经检查过它是否是NULL
  • 确实如此,但我认为这不会导致测试失败导致内存泄漏。这只是我制作循环的一种非传统方式
  • free(curr) 但有可能它永远不会得到 malloc()'d。在通过的测试中也有这样的情况,您 malloc 多次但只有一次免费。每个malloc 都应该有对应的free
  • scanf 返回成功匹配的项目数。您应该在测试 n 的值之前检查此值。
  • 在循环期间我可以在哪里释放 curr 变量?

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


【解决方案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 设置为某个负值。

【讨论】:

  • 谢谢它的工作。刚刚检查了 valgrind,没有更多错误!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多