【问题标题】:segmentation fault in linked list implementation链表实现中的分段错误
【发布时间】:2016-10-28 18:45:52
【问题描述】:

以下代码在 gcc 编译器中出现分段错误。 早些时候它工作正常,但在更新我的编译器后无法工作。 不知道它在一些在线编译器中发生了什么。

#include<stdio.h>
#include<stdlib.h>

struct node{
    int data;
    struct node* next;
};

//push function to add node at the beginning
void push(struct node** head,int data){
    //creating new node
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = NULL;

    //pointing to head if not null
    if((*head) != NULL)
        newNode->next = (*head);

    //making new node as head
    (*head) = newNode;

}

//fuction to display linked list
void display(struct node* head){
    while(head!=NULL){
        printf("%d ",head->data);
        head=head->next;
    }
    printf("\n");
}
int main(){
    struct node* head;
    push(&head,20);
    push(&head,10);
    push(&head,5);
    display(head);
    return 0;
}

【问题讨论】:

    标签: gcc linked-list segmentation-fault


    【解决方案1】:

    在 push 函数中,你检查了 head 是否为 NULL,但是当你从 main 传递 head 时,你还没有将它初始化为 NULL。

    struct node* head; 
    

    应该修改为

    struct node* head = NULL;
    

    【讨论】:

    • 用 null 初始化头部后仍然显示分段错误
    • 一旦我将 head 初始化为 NULL,它就不会在 Ubuntu 上崩溃。你能用 gdb 运行你的程序,一旦它崩溃发送回溯命令的输出..
    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2020-09-30
    • 2013-10-05
    • 1970-01-01
    • 2021-12-09
    • 2013-10-05
    相关资源
    最近更新 更多