我写了这段代码,它说有错误double free or corruption(out)
,我真的不明白我在哪里搞砸了。
int main(void) {
node *list = NULL;
node *n = malloc(4 * sizeof(node));
if (n == NULL) {
return 1;
}
n[0].number = 1;
n[0].next = NULL;
list = &n[0];
n[1].number = 2;
n[1].next = NULL;
list->next = &n[1];
n[2].number = 3;
n[2].next = NULL;
list->next->next = &n[2];
n[3].number = 4;
n[3].next = NULL;
list->next->next->next = &n[3];
for (node *tmp = list; tmp != NULL; tmp = tmp->next) {
printf("%in", tmp->number);
}
while (list != NULL) {
node *tmp = list->next;
free(list);
list = tmp;
}
}
您将节点分配为4个节点的单个块,您不能像在最后一个循环中那样一次释放一个节点。你应该:
- 单独分配每个节点
- 或只释放
n
指向的节点数组
下面是使用第一种方法的修改版本:
#include <stdlib.h>
#include <stdio.h>
typedef struct node {
int number;
struct node *next;
} node;
node *new_node(int number) {
node *n = malloc(sizeof(*n));
if (n == NULL) {
perror("new_node");
exit(1);
}
n->number = number;
n->next = NULL;
return n;
}
int main(void) {
node *list;
list = new_node(1);
list->next = new_node(2);
list->next->next = new_node(3);
list->next->next->next = new_node(4);
for (node *tmp = list; tmp != NULL; tmp = tmp->next) {
printf("%in", tmp->number);
}
while (list != NULL) {
node *tmp = list->next;
free(list);
list = tmp;
}
return 0;
}