Pop Function In Linked List Stack Results in Segmentation Fault- C

走远了吗. 提交于 2021-01-28 20:03:09

问题


I'm creating a stack using a linked list in C. The code is as follows:

struct node{
    int xposition;
    int yposition;
    struct node* next;
};

void pushToTop(struct node** hd, int x, int y){
    struct node* curr= *hd;
    struct node* prev=NULL;

    while(curr!=NULL){
        prev=curr;
        curr= curr->next;   
    }
    struct node* ptr= (struct node*)malloc(sizeof(struct node));
    ptr->xposition=x;
    ptr->yposition=y;
    ptr->next=curr;

    if(prev==NULL){
        *hd= ptr;}
    else{
        prev->next=ptr;
    }
}

void popFromTop(struct node** hd ){

    struct  node* curr= *hd;
    struct node* prev=NULL;
    while ( curr->next !=NULL) {
        prev=curr;
        curr=curr->next;
    }

    free(curr);
    prev->next= NULL;

}

The Push function works 100% of the time. The pop function works if there are multiple values in the stack, but results in a segmentation fault when there is a single value in the stack. According to my debugger, the issue is in the popFromTop method with

prev->next=NULL; 

Could someone please help me understand what the issue is?


回答1:


As already mentioned in comments by @DavidSchwartz. Add if condition.

void popFromTop(struct node** hd ){

    struct  node* curr= *hd;
    //Base condition to handle empty list
    if(*hd == NULL)
        return;

    struct node* prev=NULL;
    while ( curr->next !=NULL) {
        prev=curr;
        curr=curr->next;
    }

    free(curr);
    if(prev != NULL)
       prev->next= NULL;
    else 
       *hd = NULL;

}



回答2:


If there is only one node, in pop() prev is always NULL. So put a condition before prev->next = NULL.

Also there is one more bug: if there are 0 nodes, curr is also NULL in pop() so you might want to handle that too.



来源:https://stackoverflow.com/questions/39784052/pop-function-in-linked-list-stack-results-in-segmentation-fault-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!