繁体   English   中英

分段故障

[英]Segmentation fault

将节点添加到升序的链表中

我在这里看到过类似的内容,但并没有帮助我。 因此,无论我在哪里出错,都请纠正我。

        #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");
        }

运行此代码时,o / p是:

1

分段故障(核心已转储)

请帮我,如何解决这个问题

罪魁祸首是这条线:

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

在评估它之前,您没有检查temp->link是否为NULL 更改为:

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

通过短路评估确保安全。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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