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
,从而永久性地丢失该存储而从未使用过它。这毫无意义。