user3785612 user3785612 - 11 months ago 55
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;

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)
inserer (3,tete);
But it keeps giving segmentation fault.
Help would be appreciated.

Answer Source

tete->suiv is used uninitialized in

cour = tete->suiv;


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


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