C - 链接列表段故障

时间:2017-03-30 05:13:02

标签: c linked-list segmentation-fault

将元素放入链接列表后,当我想访问它们时,我遇到了分段错误。我尝试从头部插入(头部是tete),当读取元素时我只在该函数中没有问题

这是导致分段错误错误的行:

if((p->ID.num)>(p2->ID.num))




#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <conio.h>

        typedef struct identifiant//identifiant
        {
            char section[50];
            int num;
        }identifiant;

         typedef struct Date //DATE
        {
            int jj;
            int mm;
            int an;
        }Date;

           typedef struct notes
        {
            float note;
            struct notes* nnext;
        }notes;

          typedef struct LTE
        {
         identifiant ID;
         char Nom[25];
         char Prenom[25];
         Date Date_naissance;
         notes* Tnotes;
         float Moy;
         struct LTE* next;
        }LTE;

         typedef struct coefs
        {
            int coef;
            struct coefs* next;
        }coefs;
           coefs* COEF;
       LTE* tete;


    int main()
    { int NE,NN;

           LTE* p;
           LTE* n;
           LTE* m;



         coefs* q;
       int i,x;
       x=0;

           NE = Saisie_NE();
         NN = Saisie_NN();

         {
         tete=(LTE*)malloc(sizeof(LTE));
         tete->next=0 ;
         Saisie_E(1,tete,NN);
         for(i=2;i<=NE;i++)
          {
           LTE* tmp=(LTE*)malloc(sizeof(LTE));
           Saisie_E(i,tmp,NN);
           tmp->next=tete;
           tete=tmp;
           }
         }....
         //remplir tabeleau des coefs
         {
          COEF=(coefs*)malloc(sizeof(coefs));
          COEF->next=0 ;
          q=COEF;
         for(i=0;i<NN;i++){
           Saisie_coef(i+1,q,NN,&x);
           coefs* tmp=(coefs*)malloc(sizeof(coefs));
           q->next=tmp;
           q=q->next;
         }
         q->next=0;
         }
         //everything works fine until the this function↓↓↓
         {
             p=tete;


        Trier(p,NE);
     }

//here is the functuion ty guys sorry for bad presentation


    void Trier(LTE* p,int NE)
    {
       int tr,i;
       LTE* q;
       LTE* p1;
       LTE* p2;
       p1=p;
    i=0;
    while(tr!=1)
    {   tr=1;
        p=p1;
        for(i=0;i<NE;i++)
        {   p2=p->next;
    //here is the segment fault error

            if((p->ID.num)>(p2->ID.num)) 
     {q=p->next->next;
                p->next->next=p;
                p->next=q;
                tr=0;
                }
     p=p->next;
        }
    }

1 个答案:

答案 0 :(得分:1)

问题在于以下循环。在循环迭代期间,当i == (NE-1)时,p将指向最后一个节点,p->next将为NULL,并将其分配给p2。因此,访问p2->ID.num会导致细分错误。

您可以添加对p2!=NULL的检查,也可以修改循环逻辑以防止这种情况发生。

 for(i=0;i<NE;i++)
    {   p2=p->next; /* ==> When p becomes the last node, p2 will become NULL */
//here is the segment fault error

        if((p->ID.num)>(p2->ID.num)) 
 {q=p->next->next;
            p->next->next=p;
            p->next=q;
            tr=0;
            }
 p=p->next;
    }