1

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;
}
9
  • 2
    Most likely because it has one or more bugs, which you can find using a debugger. Commented Aug 28, 2017 at 17:32
  • Don't malloc in C++. Commented Aug 28, 2017 at 17:33
  • 4
    while(current->data<data&&current!=NULL) should be while(current!=NULL && current->data < data) Commented Aug 28, 2017 at 17:36
  • this is a run time question, but the posted code does not compile. Please post a minimal reproducible example Commented Aug 29, 2017 at 5:16
  • what is the definition of: struct node? Commented Aug 29, 2017 at 5:21

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
}

Comments

0

if this statement fails on the first iteration:

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

then this statement:

prev->next=new_node;

will be accessing an offset from address 0 which will almost always result in a seg fault event.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.