Reputation: 597
After putting elements in my linked list, when i want to acces them i got a segmentation fault. I try to insert from the head(head is tete), when reading the element I have no problems only in that function
here is the line that causes segmentation fault error:
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;
}
}
Upvotes: 0
Views: 69
Reputation: 24895
The problem lies in the below loop. During the loop iterations, when i == (NE-1)
, p
will be pointing to the last node and p->next
will be NULL which gets assigned to p2
. So, accessing p2->ID.num
leads to segmentation fault.
You can either add a check for p2!=NULL
or modify your loop logic to prevent this from happening.
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;
}
Upvotes: 1