-2

I m writing a function to insert a number in a sorted linked list in C++. However, I am getting "Segmentation Fault" when I run it. Can anyone explain why it is so?

    Node * insertInSorted(Node * head, int data)
{
    Node * curr = head;
    Node * a = new Node(data);
    
    while(curr->next->data < a->data || curr->next != NULL)
    {
        curr = curr->next;
    }
    
    Node * temp = curr->next;
    
    curr->next = a;
    a->next = temp;
    
    return head;
}
Ashish
  • 5
  • 5
  • 3
    `curr->next != NULL*`is too late. Learn how to use a debugger [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – 273K May 31 '21 at 06:07
  • To expand on @S.M's answer, you are accessing the property `data` of `curr->next` prior to checking, whether `next` is even valid. As such, at the end of the list, you are accessing a NULL pointer, which leads to the segfault. Simply switch the conditions around and the problem should disappear (due to short circuiting conditions) – Refugnic Eternium May 31 '21 at 06:09
  • Hi, thanks for commenting. I tried doing what you suggested, but I am still getting Seg Fault. – Ashish May 31 '21 at 06:12
  • Well, that was just the most obvious error. How about you run the source file through a debugger of your choice and tell us, where the segfault actually occurrs? If you watch the involved variables carefully, you might already figure out the problem yourself. As a little additional hint, you may want to make sure, that 'curr' does not end up being 'NULL' at the end of the loop. – Refugnic Eternium May 31 '21 at 06:15

1 Answers1

1

while(curr->next->data < a->data || curr->next != NULL)

That is obviously wrong. The condition you want is:

while(curr->next != NULL && curr->next->data < a->data)

  1. The next node must exist and
  2. Must have data smaller than the data you are inserting.

The function still wouldn't work correctly (you never insert anything before head, even if that's where the insertion should happen), but at least your crash should be gone.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362