我写了这段代码,它说有错误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("%i\n", tmp->number);
    }

    while (list != NULL) {
        node *tmp = list->next;
        free(list);
        list = tmp;
    }
}

推荐答案

如果将 node 分配为由4个 node 组成的单个块,则无法像在最终循环中那样一次释放一个 node .您应该:

  • 分别分配每个 node
  • 或者仅释放由n指向的 node array.

以下是使用第一种方法的修改版本:

#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("%i\n", tmp->number);
    }

    while (list != NULL) {
        node *tmp = list->next;
        free(list);
        list = tmp;
    }
    return 0;
}

C++相关问答推荐

函数指针始终为零,但在解除引用和调用时有效

如何确保内存分配在地址附近?

常数函数指针优化

如何设置指针指向在函数中初始化的复合文字中的整数?

如何将已分配的数组(运行时已知的大小)放入 struct 中?

为什么sscanf不能正确地从这个字符串格式中提取所有数字?

加密解密工作正常,但返回错误0x80090005

理解C版宏(看起来像未声明的变量?)

如何使解释器存储变量

<;unistd.h>;和<;sys/unistd.h>;之间有什么区别?

S和查尔有什么不同[1]?

在vfork()之后,链接器如何在不 destruct 父内存的情况下解析execve()?

Wcstok导致分段故障

我正在try 将QSORT算法实现为C++中的泛型函数

用于计算位数和的递归C函数

共享内存未授予父进程权限

GCC认为这是一个VLA是对的吗?

C struct 中的冒泡排序

为什么孤儿进程在 Linux 中没有被 PID 1 采用,就像我读过的一本书中声称的那样?

如何为avr atmega32微控制器构建C代码,通过光电二极管捕获光强度并通过串行通信传输数据