Pop Function In Linked List Stack Results in Segmentation Fault- C
<p>I'm creating a stack using a linked list in C. The code is as follows:</p>

<pre><code>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-&gt;next;   
    }
    struct node* ptr= (struct node*)malloc(sizeof(struct node));
    ptr-&gt;xposition=x;
    ptr-&gt;yposition=y;
    ptr-&gt;next=curr;

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

void popFromTop(struct node** hd ){

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

    free(curr);
    prev-&gt;next= NULL;

}
</code></pre>

<p>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 </p>

<pre><code>prev-&gt;next=NULL; 
</code></pre>

<p>Could someone please help me understand what the issue is?</p>