I am trying to make a sorted doubly-linked list with a function inserer() to insert values into it.
I write the whole program as follows :
#include <stdio.h>
#include <stdlib.h>
typedef struct bi{
int val;
struct bi *prec;
struct bi *suiv;
}bil;
void inserer (int v, bil *tete)
{
bil *cour, *elt;
cour = tete->suiv;
while (cour != tete && cour->val < v)
cour = cour->suiv;
elt = (bil*) malloc(sizeof(bil));
if (elt)
{
elt->val = v;
(cour->prec)->suiv = elt;
elt->suiv = cour;
elt->prec = cour->prec;
cour->prec = elt;
}
}
int main()
{
bil* tete;
/*Creation tete fictif*/
tete = (bil*) malloc (sizeof(bil));
tete->prec = tete;
tete->prec = tete;
inserer (3,tete);
return 0;
}
Then I try to use the function and insert a value (3 in the example)
with inserer (3,tete);
But it keeps giving segmentation fault.
Help would be appreciated.
3 Answers 3
tete->suiv
is used uninitialized in
cour = tete->suiv;
Change
tete->prec = tete;
tete->prec = tete;
to
tete->prec = tete;
tete->suiv = tete;
answered Aug 25, 2016 at 20:09
1 Comment
user3785612
You're awesome, How didn't I see that. Thank you
You are getting segmentation fault because of cour = tete->suiv;
Initially both the pointer should be assigned to tete
cour->suiv = tete;
cour->suiv = tete;
answered Aug 25, 2016 at 20:12
Comments
You never set tete->suiv
to anything. In main
you probably meant
tete->prec = tete;
tete->suiv = tete;
Comments
lang-c