This code creates a binary search tree but it runs sometimes normally and sometimes makes errors, even without changing anything in the code.
I can't get why this happening, what's the mistake ?
Even I changed the function that I used to create the tree from recursive to iterative but the same results.
#include <stdio.h>
#include <stdlib.h>
typedef struct sommet{
struct sommet * fg;
int val;
struct sommet * fd;
}sommet;
typedef sommet* ptrm;
ptrm creearbre(ptrm arbre,int ele);
void impression(ptrm arbre);
ptrm creearbre_rec(ptrm arbre,int ele);
int main()
{
ptrm arbre=NULL;
int tarbre,n;
printf("entre la taille de l'arbre:");
scanf("%d",&tarbre);
for(int i=0;i<tarbre;i++)
{
printf("entre l'element %d: ",i+1);
scanf("%d",&n);
arbre=creearbre_rec(arbre,n);
}
impression(arbre);
return 0;
}
ptrm creearbre_rec(ptrm arbre,int ele)
{
if(arbre==NULL)
{
arbre=malloc(sizeof arbre);
arbre->val=ele;
arbre->fd=NULL;
arbre->fg=NULL;
}
else if(arbre->val > ele)
arbre->fg=creearbre_rec(arbre->fg,ele);
else
arbre->fd=creearbre_rec(arbre->fd,ele);
return arbre;
}
void impression(ptrm arbre){
if(arbre != NULL){
printf(" %d -->", arbre->val);
impression(arbre->fg);
impression(arbre->fd);
}
}
ptrm creearbre(ptrm arbre,int ele){
ptrm p,q=arbre,r=NULL;
p=malloc(sizeof arbre);
p->val=ele;
p->fd=NULL;
p->fg=NULL;
if(arbre==NULL){
arbre=p;
}
else{
while(q!=NULL){
r=q;
if(ele > q->val)
q=q->fd;
else
q=q->fg;
}
if(ele > r->val)
r->fd=p;
else
r->fg=p;
}
return arbre;
}
The program has undefined behavior due to using an invalid size in the allocation of memory in statements
arbre=malloc(sizeof arbre);
and
p=malloc(sizeof arbre);
There are allocated memory for pointers instead of objects of the structure type.
You need to write
arbre=malloc(sizeof *arbre);
p=malloc(sizeof *arbre);