Alcore Alcore - 2 months ago 7
C Question

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

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?

Answer

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;

}