释放单链表内存时出现Invalid free()错误

Invalid free() error when freeing memory of a singly-linked list

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

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

最后一个元素的下一个字段为 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 个分配和 13 个释放,所以某处有一个游离的释放...

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

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

(我在phone,对任何错误表示歉意。)