Search code examples
clinked-listsingly-linked-listnull-pointerfunction-definition

segmentation fault (core dumped) when adding this feature


I try to add a function to an Code that already works. After adding my function, the code is still executed, but when I choose case 3, I get the error segmentation fault (core dumped) I get the segmentation fault (core dumped) error, if i choose case 3

Here is my Function to case 3:

typedef struct Note_
{
    int data;
    struct Note_ *next;
} Note;

Note *head= NULL;
int number= 0;


void deleteNote(int x){
    
 Note *t = head;
 Note *prev;

 if(t == NULL){
 printf("List already empty.\n");
 }
 while(t != NULL && t->data == x){
 head = t->next;
 free(t);
 t= head;
 printf("Note %d deleted.\n", x);
 }
 
 while(t != NULL){
 while(t != NULL && t->data != x){
 prev = t;
 t = t->next;
 }
 prev->next = t->next;
 free(t);
 t = prev->next;
 }
 
 }

Solution

  • In this code snippet

            prev->next = t->next;
            free(t);
            t = prev->next;
    

    the pointer t can be equal to NULL after the preceding while loop.

        while(t != NULL && t->data != x)
        {
            prev = t;
            t = t->next;
        }
    

    So using a null pointer to access memory like in this statement

             prev->next = t->next;
    

    invokes undefined behavior.

    You need to check whether after the while loop the pointer t is not equal to NULL.