简体   繁体   中英

Segmentation fault

Adds a node to an ascending ordered linked list

I have seen some similar stuff here but that didnt help me. So please correct me wherever I am wrong.

        #include<stdio.h>
        #include<stdlib.h>
        struct node
        {
          int data;
          struct node* link;
        };
         struct node* head = NULL;
        void add(int);
        void print();
        int main()
        {
          add(1); print();
          add(2); print();
          add(5); print();
          add(4); print();
          add(3); print();
        return 0;
        }
***/* if list is empty or if new node is to be inserted before the first node*/***
         void add( int num)
        {  
           struct node* temp;
           temp =  head;
           struct node* newNode = (struct node*)malloc(sizeof(struct node));
           newNode->data = num;
           newNode->link = NULL;
           if((head == NULL)||( head->data > num))
               {
                 newNode->link = head;
                 head = newNode;
               }
           else
              {
  ***/* traverse the entire linked list to search the position to insert the new node*/***
               while(temp!=NULL)
               {
                if(temp->data <= num && ( temp->link->data > num || temp->link == NULL))
                    {
                       newNode->link = temp->link;
                       temp->link = newNode;
                       return;
                    }
                  temp= temp->link;
                }
               }
             }
    ***/*Display the content of the linked list*/***    
          void print()
        {
           struct node* temp;
           temp = head;
           while(temp!=NULL)
            {
              printf("%d", temp->data);
              temp=temp->link;
            }
           printf("\n");
        }

While running this code o/p is :

1

Segmentation Fault (core dumped)

Please help me, how to solve this problem

The culprit is this line:

if(temp->data <= num && ( temp->link->data > num || temp->link == NULL))

You are not checking that temp->link is not NULL before evaluating it. Change it to:

if(temp->data <= num && ( temp->link == NULL || temp->link->data > num))

to make it safe by taking advantage of short-circuit evaluation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM