我一直在尝试从链接列表中弹出一个元素,但我得到了这个奇怪的输出。
这是给定的骨架代码:
char* pop() {
}
这就是我现在所拥有的:
char* pop() {
char* val;
struct node* current;
if( head != NULL){
val = head -> name;
current = head -> next;
free(head);
head = current;
}
return(val);
}
这是main.c:
node *head = NULL; //globally accessible
int main(){
printf("Printing an empty list\n");
print_list();
printf("\nPushing Kelsier...\n");
push("Kelsier");
print_list();
printf("\nPushing Vin. Should be: Vin Kelsier\n");
push("Vin");
print_list();
char* vin = pop();
free(vin);
pop();
print_list();
这是奇怪的输出:
*** glibc detected *** ./linked_list: munmap_chunk(): invalid pointer: 0x000000000040098d ***
这一行之后是一些奇怪的东西和文件夹路径
问题是程序无需这两行即可运行:
char* vin = pop();
free(vin);
当我只用 pop();
替换它们时,但是这两行是给定的,我不应该给它们。
这是推送:
void push(char *name) {
struct node* newNode;
newNode = malloc (sizeof (struct node));
newNode->name = name;
newNode->next = head;
head = newNode;
}
最佳答案
pop
返回与传递给 push
相同的指针:字符串文字 "Vin"
的地址。您无法free
字符串文字,因为您不是从malloc
获取它。
如果 pop
返回的值应该是free
-able,那么 push
将必须分配一个字符串,而不仅仅是复制一个指针。例如,您可以替换
newNode->name = name;
与
newNode->name = strdup(name);
关于c - 从 C 中的链表中弹出一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31712445/