Reputation: 1
Here is my C code that aims to make a linked list of n element ""n is read from keyboard"" building is 100% successful but when executing an error message appears and the program stops working.
typedef struct maillon* ptr;
struct maillon {
int vale;
ptr adr;
};
ptr Allouer( ptr p )
{
return malloc( sizeof(struct maillon) );
}
void Aff_val( ptr p, int v )
{
p->vale= v;
}
void Aff_adr( ptr p, ptr q )
{
p->adr = q;
}
void main()
{
ptr debut, courant, fin;
int n, vale;
scanf("%d",&n);
Allouer(debut);
Aff_val(debut,5); //5 is a value that contains my 1st element
courant=debut;
for (int i=1;i<=n;i++)
{
Allouer(fin);
Aff_adr(courant,fin);
printf("enter the value");
scanf("%d",&vale);
Aff_val(fin,vale);
courant=fin;
}
Aff_adr(courant,NULL);
}
Upvotes: 0
Views: 80
Reputation: 206577
The problem is in the line
Allouer(debut);
The value returned from Allouer
is not used. Not only do you not see debut
set to a valid pointer but also the program suffers from a memory leak. Change it to:
debut = Allouer(debut);
Suggestion for further improvement.
Allouer
does not use the input argument. It will be better to remove it.
ptr Allouer()
{
return malloc( sizeof(struct maillon) );
}
Then, it's usage can be changed to:
debut = Allouer();
Upvotes: 3