首页 > 解决方案 > 释放单链表的内存时出现无效的 free() 错误

问题描述

在 C 中,我试图释放单链表中的所有内存,其结构是:

typedef struct node {
  char *data;
  int weight;
  struct node *next;
} Node;

最后一个元素的 next 字段为NULL。每个节点及其数据字段都是动态分配的。到目前为止,我的功能是:

void free_list(Node *const list) {
  Node *current = list;
  Node *temp;

  while (current != NULL) {
    temp = current;
    current = current->next;

    free(temp->data);
    free(temp);
  }
}

当我在 valgrind 上运行我的一项测试时,我可以看到所有堆块都被释放,所以肯定没有内存泄漏,这是目标。但是,valgrind 给我一个Invalid free()错误,我不知道为什么。奇怪的是,当我删除该行时free(temp),此错误消失了,但我现在正在泄漏内存。所以这条线既是必要的,也是有问题的。我哪里出错了?

添加更多代码以制作可重现的示例。

使用以下命令将节点添加到列表中:

unsigned int add(Node *const head, const char new_data[], unsigned int weight) {
  Node *current = head;
  Node *new_node = malloc(sizeof(Node));
  char *new_data_copy = malloc(strlen(new_data) + 1);

  strcpy(new_data_copy, new_data);

  /* this loop moves the current pointer to the point where the new element
  should be inserted, since this is a sorted list. */
  while (current->next != NULL && current->next->weight < weight) {
    current = current->next;
  }

  new_node->data = new_data_copy;
  new_node->weight = weight;
  new_node->next = current->next
  current->next = new_node;

  return 1;
}

列表总是在我调用任何东西之前初始化,值为数据NULL、权重和下一个字段。-1NULL

如您所见,列表是从最低重量到最高重量的顺序。我可能需要解决更多错误,这就是为什么我试图减少问题以将我的特定问题与 valgrind 隔离开来。

编辑:valgrind 向我展示了 12 个 allocs 和 13 个 frees,所以某处有一个流浪的 free ......

编辑2:头部是如何创建的?主要Node head是先声明然后initialize(&head)调用。

void initialize(Node *const head) {
  head->data = NULL
  head->weight = -1;
  head->next = NULL
}

一个主要的

#include "structure.h"
int main(void) {
  Node head;
  char *data[] = {"A","B","C","D","E","F"};
  int weight[] = {1, 2, 3, 4, 5, 6};
  int i;

  initialize(&head);

  for (i = 0; i< 6; i++) {
    add(&head, data[i], weight[i]);
  }

  free_list(&head);
  return 0;
}

标签: cvalgrindfreesingly-linked-list

解决方案


free仅适用于在堆上分配的东西malloc。如果你在堆栈上分配一些东西,它的内存就会为你管理。

大概发生了这样的事情。

// The first Node is allocated on the stack
Node list = { .data="test", .weight=23 };

// The rest are heap allocated.
add(list, "new", 42);

// free_list calls free() on all of them
free_list(list);

您可以通过提取代码以从add.

Node *new_node( const char *data, int weight ) {
    Node *node = malloc(sizeof(Node));
    node->data = strdup(data);
    node->weight = weight;
    return node;
}

然后这可以用来初始化列表,也可以用来传递给add。这使得确保每个节点都在堆上分配更容易。它使添加更有用,它可以添加任何现有节点。

Node *add(Node *current, Node *new_node) {
  while (current->next != NULL && current->next->weight < weight) {
    current = current->next;
  }

  new_node->next = current->next;
  current->next = new_node;

  // Might be useful to know where the node was added.
  return current;
}

Node *list = new_node("test", 23);
add(list, new_node("new", 42));
free_list(list);

(我正在打电话,为任何错误道歉。)


推荐阅读