2

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.

asked Aug 25, 2016 at 20:06

3 Answers 3

4

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

You're awesome, How didn't I see that. Thank you
3

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

0

You never set tete->suiv to anything. In main you probably meant

tete->prec = tete;
tete->suiv = tete;
answered Aug 25, 2016 at 20:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.