Home > database >  Why does it say "double free or corruption (out) Aborted"
Why does it say "double free or corruption (out) Aborted"

Time:07-17

I wrote this code and it says that there is error double free or corruption(out) I don't really understand where I messed up.

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

CodePudding user response:

You allocate the nodes as a single block of 4 nodes, you cannot free them one at a time as you do in the final loop. You should either:

  • allocate each node separately
  • or only free the node array pointed to by n.

Here is a modified version using the first approach:

#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;
}
  • Related