Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 对链表排序时出现分段错误_C_Sorting - Fatal编程技术网

C 对链表排序时出现分段错误

C 对链表排序时出现分段错误,c,sorting,C,Sorting,每次我运行这个循环时,在循环的第二次迭代中都会出现分段错误 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)

每次我运行这个循环时,在循环的第二次迭代中都会出现分段错误

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);
        }
    }
} 
每当我给它一个列表-例如4,1,9,6
它只交换4和1,当它是交换9和6的迭代时,它显示和分割错误

执行
temp=new1->next后
temp
如果
new1
是列表的最后一个节点,则可以是
NULL
。当
temp
NULL
时,当您访问此行
printf(“temp变量:%d\n”,temp->data”)中的字段时,它会引发一个段错误

我建议您花些时间阅读Eric Lippert的文章,并学习如何使用调试器捕获这样的崩溃。这至少可以帮助您找到代码中崩溃发生的位置。下一步是在调试器中逐行检查代码,以找出可能发生这种情况的原因。很可能有一个指针没有正确更新,或者根本没有初始化。可能是不相关的,但是内存泄漏(两个
malloc
s代表
temp
temp1
)谈论指针,
new=start->next将导致内存泄漏。首先使
new
指向某个内存,然后使其指向另一个内存,从而丢失原始指针。我还建议您阅读,关于强制转换
malloc
的结果。您的排序例程不应该分配任何内容,因此您现在拥有的代码没有意义,应该立即废弃。注意:在
if
语句中对
malloc
的两个调用,在分配
temp
temp1
的地方,只不过是内存泄漏,因为在分配存储之后,您会立即将其他值分配给
temp
temp1
,从而永久性地丢失该存储而从未使用过它。这毫无意义。