gpt4 book ai didi

C 错误 : munmap_chunk(): invalid pointer

转载 作者:太空宇宙 更新时间:2023-11-04 02:38:08 35 4
gpt4 key购买 nike

我在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。 add_node 函数中的 curr->next = new_node; 行导致运行时错误。是什么导致了这个错误?如何解决?

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

Aborted (core dumped)

最佳答案

您只能释放 malloc 返回的指针。

你在做什么

free(curr->value);

curr->value 恰好指向字符串文字 "hello" 时,它不是由 malloc 分配的。

您可以通过以下任一方法修复它:

  • 使用 malloc(或使用 malloc 的其他函数,例如 strdup)分配值
  • 释放值。 (但是,如果您有一些值需要释放,而一些不需要,您的程序需要记住哪些值需要释放)

关于C 错误 : munmap_chunk(): invalid pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34887157/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com