このループを実行するたびに、ループの2番目の繰り返しでセグメンテーションフォルトが発生します。リンクリストをソートする際にセグメンテーションフォルトを取得する
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を交換する反復であると、それはセグメント化の欠陥を示す。
フィールドの訪問時に、私は(https://ericlippert.com/2014/03 [小さなプログラムをデバッグする方法]あなたが読むには時間がかかるお勧めセグメントエラーが発生します/ 05/how-to-debug-small-programs /)を読んで、デバッガを使ってこのようなクラッシュをキャッチする方法を学びます。それは少なくともあなたのコード内でクラッシュが発生する場所を特定するのに役立ちます。次のステップは、デバッガでコードを1行ずつ進んで*なぜ*起こるかを調べることです。ほとんどの場合、正しく更新されないか、まったく初期化されないポインタがあります。 –
おそらく関係はありませんが、メモリがリークしています(tempとtemp1の2つの 'malloc') – UnholySheep
ポインタについて、' new = start-> next;はメモリリーク*につながります。最初に 'new'ポイントをいくつかのメモリにポイントし、次にそれをいくつかの他の*メモリを指すようにして、元のポインタを失います。 'malloc'の結果をキャストする方法については、[この古い質問とその回答](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)を読むことをお勧めします。 –