简体   繁体   English

在对链表进行排序时出现分段错误

[英]Getting A segmentation Fault in sorting a linked list

everytime I run this loop , I get a segmentation fault in the second iteration of the loop .每次运行此循环时,都会在循环的第二次迭代中遇到分段错误。

node *new,*new1;

new=(node*) malloc(sizeof(node));
new1=(node*) malloc(sizeof(node));
new = start->next;

for(;new->next != NULL;new = new->next)
{
    for(new1=new->next;new1 != NULL;new1=new1->next)
    {   //printf("LOOP\n");
        if(new->data > new1->data)   
        {
            printf("\n Swapping - new:%d and  new1:%d\n",new->data,new1->data); 
            temp = (node*) malloc(sizeof(node));
            temp1 = (node*) malloc(sizeof(node));
            temp1 = new->next;
            temp = new1->next;
            new->next = temp;
            printf("Temp var : %d\n",temp->data);
            printf("Temp1 var : %d\n",temp1->data);
            new1->next = new;

            new1 = new;
            new = temp1;
            printf("After swapping , new:%d and new1 : %d\n",new->data,new1->data);
            //        free(temp);
            //       free(temp1);
        }
    }
} 

Whenever I give a list to it - eg.每当我给它一个清单时 - 例如。 4,1,9,6 it only swaps 4 and 1 , when it is the iteration to swap 9 and 6 , it shows and segmentation fault . 4,1,9,6 只交换了4和1,当是交换9和6的迭代时,显示和segmentation fault。

After executing temp = new1->next;执行temp = new1->next; , temp could be NULL if new1 was the last node of the list. , 如果new1是列表的最后一个节点,则temp可能为NULL While temp is NULL , it would raise a segment error when you visit it's field in this line printf("Temp var : %d\\n",temp->data);虽然tempNULL ,但当您访问该行中的字段printf("Temp var : %d\\n",temp->data);时,它会引发段错误printf("Temp var : %d\\n",temp->data);

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

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