c - 从 C 中的链表中弹出一个元素

标签 c pointers linked-list

我一直在尝试从链接列表中弹出一个元素,但我得到了这个奇怪的输出。

这是给定的骨架代码:

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/

相关文章:

c - 使用链接列表没有任何错误但得到奇怪的输出

c++ - 池类抛出错误

c - Search a String in a string(字符串由用户输入)

c++ - mini6410 上的 Open Cv 和 GPIO 问题

c - 递归二叉树插入

c - 使用Python返回指向已经存在的内存地址的指针

c - c中链表中的头节点

c - 具有指定初始化程序的 MSVC12 (VS2013) 中可能存在编译器错误

C中按值调用函数

多个文件错误 : dereferencing pointer to incomplete type 中的 c 结构