user3785612 user3785612 - 3 months ago 14
C Question

Sorted doubly linked list and inserting values

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.

Answer

tete->suiv is used uninitialized in

cour = tete->suiv;

Change

tete->prec = tete;
tete->prec = tete;

to

tete->prec = tete;
tete->suiv = tete;