我在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中止(核心倾销)
答案 0 :(得分:2)
您只能free
malloc
返回的指针。
你在做什么
free(curr->value);
当curr->value
碰巧指向未由"hello"
分配的字符串文字malloc
时。
您可以通过以下方式解决此问题:
malloc
(或使用malloc
的其他功能,例如strdup
)free
该值。 (但是如果你有一些值需要free
d而某些值不需要,那么你的程序需要记住哪些值为free
)