0

Program quits completely at

while ((temp->x < new_node->x)&&(temp != NULL)) 

but it runs when written as

while((temp!=NULL) &&(temp->x < new_node->x)) 

Here is my code.

Node *insert(Node *head)
{
    Node *new_node = (Node *)malloc(sizeof(Node));
    new_node->next = NULL;
    printf("\nEnter x: ");
    scanf("%d", &new_node->x);
    if (head == NULL)
        return new_node;
    else
    {
        Node *prev = NULL, *temp = head;
        while ((temp->x < new_node->x)&&(temp != NULL))  // but, ((temp!=NULL) &&(temp->x < new_node->x)) runs 
        {
            prev = temp;
            temp = temp->next;
        }
        new_node->next = temp;
        if (prev == NULL) // Node needs to insert at beginning to maintain the sorting of Linked List
            return new_node;
        prev->next = new_node;
        return head;
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41
  • what is the goal of your program? – m3ow Nov 26 '22 at 06:12
  • This might help you, https://www.codesdope.com/blog/article/linked-lists-in-c-singly-linked-list/ – m3ow Nov 26 '22 at 06:13
  • You should always confirm that a node exists before checking its value, otherwise you would be trying to dereference a NULL pointer. More info: [What exactly is meant by "de-referencing a NULL pointer"?](https://stackoverflow.com/questions/4007268/what-exactly-is-meant-by-de-referencing-a-null-pointer) – David Ranieri Nov 26 '22 at 06:20
  • [Order of execution for an if with multiple conditionals](https://stackoverflow.com/questions/2456086/order-of-execution-for-an-if-with-multiple-conditionals) – Abra Nov 26 '22 at 06:23

1 Answers1

0

Conditions in a loop or an if statement with && are evaluated strictly left-to-right, and the RHS is not evaluated unless the LHS evaluates to true. You have:

while ((temp->x < new_node->x) && (temp != NULL))

The condition temp->x < new_node->x is evaluated before temp != NULL. But, if temp is null, the first comparison will fail on most systems because accessing via a null pointer is undefined behaviour and normally causes a segmentation fault.

By contrast, when you write:

while ((temp != NULL) && (temp->x < new_node->x)) 

The code first checks for the null pointer, and if the pointer is null, does not evaluate the RHS condition, so the crash is averted.

The moral is always to check for null pointers before trying to access data through the pointer. Obviously, if the pointer cannot be null, there is no need to test it before using it. Sometimes, if the pointer should never be null, it may be beneficial to assert that the pointer is not null:

assert(temp != NULL);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278