Valeriy
Valeriy

Reputation: 1435

C error: munmap_chunk(): invalid pointer

I wrote linked list on C.

#define MAX_TOKEN_LENGTH 256

struct node {
    char *value;
    struct node *next;
};

struct node *new_list() {
    struct node *head = (struct node*) malloc(sizeof(struct node));
    head->value = (char*) malloc(MAX_TOKEN_LENGTH * sizeof(char));
    head->next = NULL;
    return head;
}

void add_node(struct node *head, char *value) {
    struct node *next;
    struct node *curr = head;
    struct node *new_node;

    while(curr->next != 0) {
        curr = curr->next;
    }

    new_node = (struct node*) malloc(sizeof(struct node));
    new_node->value = value;
    new_node->next = NULL;
    curr->next = new_node;
}

void delete_list(struct node* list) {
    struct node *curr = list;
    
    while (curr) {
        struct node* next = curr->next;
        free(curr->value);
        free(curr);
        curr = next;
    }
}

struct node *list = new_list();
add_node(list, "hello");
delete_list(list);

Compiler: GCC. Line curr->next = new_node; in add_node function causes an runtime error. Which leads to this error? How to fix it?

Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000400864

Aborted (core dumped)

Upvotes: 1

Views: 10520

Answers (1)

You can only free a pointer that was returned by malloc.

You are doing

free(curr->value);

when curr->value happens to point to the string literal "hello", which was not allocated by malloc.

You could fix it by either:

  • Allocating the value with malloc (or another function that uses malloc, such as strdup)
  • Not freeing the value. (But if you have some values that need to be freed and some that don't, your program needs to remember which ones to free)

Upvotes: 3

Related Questions