C错误:munmap_chunk():指针无效

时间:2016-01-19 21:22:27

标签: c

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

编译:GCC。 curr->next = new_node;函数中的行add_node会导致运行时错误。导致此错误?如何解决?

  <。> ./a.out':munmap_chunk()出错:无效指针:0x0000000000400864

     

中止(核心倾销)

1 个答案:

答案 0 :(得分:2)

您只能free malloc返回的指针。

你在做什么

free(curr->value);

curr->value碰巧指向未由"hello"分配的字符串文字malloc时。

您可以通过以下方式解决此问题:

  • 使用malloc(或使用malloc的其他功能,例如strdup
  • 分配值
  • free该值。 (但是如果你有一些值需要free d而某些值不需要,那么你的程序需要记住哪些值为free