Question: This is a function to insert into a sorted linked list but it is showing segmentation fault (SIGSEGV)

```
void sortedInsert(struct node **head_ref, int data) {
    struct node *new_node, *prev, *current;
    new_node = (struct node*)malloc(sizeof(struct node));
    new_node->data = data;
    new_node->next = NULL;
    if (*head_ref == NULL || (*head_ref)->data > data) {
        new_node->next = *head_ref;
        *head_ref = new_node;
        return;
    }
    current = *head_ref;
    prev = NULL;
    while (current->data < data && current != NULL) {
        prev = current;
        current = current->next;
    }
    prev->next = new_node;
    new_node->next = current;
}

```

Answer: 
Most likely the segmentation fault here is because of the statement: 

```
while(current->data<data&&current!=NULL)
    {
        prev=current;
        current=current->next;
    }

```

The current pointer here is being dereferenced without being checked for NULL. You should try changing the condition to `while(current && current->data<data)` so that the pointer gets checked for NULL before being dereferenced.
The bug is here: `while (current->data < data && current != NULL)`. The pointer must be checked against `NULL` **before** it is dereferenced:

```
while (current != NULL && current->data < data)

```

Note that this function can be simplified with a single loop:

```
void sortedInsert(struct node **head_ref, int data) {
    struct node *new_node;
    while (*head_ref && (*head_ref)->data <= data) {
        head_ref = &(*head_ref)->next;
    }
    new_node = malloc(sizeof(struct node));
    if (new_node == NULL) {
        /* handle the error */
        ...
    } else {
        new_node->data = data;
        new_node->next = *head_ref;
        *head_ref = new_node;
    }
}

```