【问题标题】:Printing C linked list produces memory leak打印 C 链表会产生内存泄漏
【发布时间】:2019-03-12 01:47:56
【问题描述】:

我正在使用 Heapusage,它是 Valgrind 的替代品。当我在主函数中打印我的链表时,它会产生内存泄漏(当打印函数被注释时,一切都很好)。我试图找出问题所在,但打印功能太简单了,要么我的堆分析器出错了,要么问题很简单,我找不到。

typedef struct Point {
  int x, y;
  struct Point *next;
} Point;

Point *NewPoint(const int x, const int y, Point *head) {
  Point *point = (Point *)malloc(sizeof(Point));
  point->next = NULL;
  point->x = x;
  point->y = y;
  if (head == NULL) {
    head = point;
  } else {
    Point *current = head;
    while (current->next != NULL) {
      current = current->next;
    }
    current->next = point;
  }
  return head;
}

void FreeList(Point *head) {
  Point *current = head;
  while (current != NULL) {
    Point *tmp = current;
    current = current->next;
    free(tmp);
  }
}

void PrintList(Point *head) {
  while (head) {
    printf("[%d, %d]\n", head->x, head->y);
    head = head->next;
  }
}

int main() {
  Point *head = NULL;
  head = NewPoint(2, 3, head);
  PrintList(head);
  FreeList(head);
  return 0;
}

【问题讨论】:

  • 你的工具具体说什么是泄漏,在哪一行?
  • 您的代码有问题。 head 需要通过引用传递,即 &head 并且您的函数原型需要是 Point *NewPoint(const int x, const int y, Point **head) 并且此函数中需要进行许多更改以处理此基本更改!如果您将 head 更改为全局指针并且不将其作为参数传递给函数,则您当前的代码可以正常工作。
  • @hesham_EE C 没有通过引用。为什么函数参数一定需要从*head 更改为**head?
  • @Miket25,我的意思是顺便说一句,很抱歉我对这个词的使用不准确。他需要更改为**head,因为head 已经是一个指针Point *head,他需要在另一个函数中更改此指针的值。所以,他需要传递一个指向该指针的指针,因此是**head。
  • 哦!我现在明白了,他归还了新头。我以为他更新了被调用函数中的头部。我的错!

标签: c memory linked-list


【解决方案1】:

你没有泄漏,用 valgrind-3.14.0.GIT 测试过

==13568== Memcheck, a memory error detector
==13568== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==13568== Using Valgrind-3.14.0.GIT and LibVEX; rerun with -h for copyright info
==13568== Command: ./a.out
==13568==  [2, 3]
==13568== 
==13568== HEAP SUMMARY:
==13568==     in use at exit: 0 bytes in 0 blocks
==13568==   total heap usage: 2 allocs, 2 frees, 1,040 bytes allocated
==13568== 
==13568== All heap blocks were freed -- no leaks are possible
==13568== 
==13568== For counts of detected and suppressed errors, rerun with: -v
==13568== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

【讨论】:

  • 我也做了同样的事情,它也没有向我报告任何错误(valgrind-3.11.0)!
  • @DavidWichterle:为什么不接受这个答案,因为这会结束你的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 2017-09-26
  • 1970-01-01
相关资源
最近更新 更多