Using "->" to navigate structs with pointers

248 views Asked by At

I am trying to create a phone book, which is a binary search tree which has a linked list on the end of each leaf, but, I have encountered a "Segmentation fault (Core dumped)" error. I have a feeling it is caused by my "makenode" function which creates the first node of the tree. My structs are the following

typedef struct number{
    char number [20];
    struct number *next; 
} Number;

typedef struct list {
    Number *first, *last;
} List;

typedef struct tree {
    char name[20];
    struct tree * left;
    struct tree * right;
    List * next;
} Tree;

And my makenode function is

Tree *makenode (char name[20], Tree *l, Tree *r, Number e) {
    Tree *newnode;
    newnode = malloc( sizeof(Tree));
    strncpy(newnode->name,name,19);
    newnode->next=malloc(sizeof(List));
    newnode->next->first=malloc(sizeof(Number));
    strncpy(newnode->next->first->number,e.number,11);
    newnode->left = l;
    newnode->right = r; 
return newnode;
}

I was just hoping for advice on whether the line

strncpy(newnode->next->number,e.number,11);

is the line causing the problem, and maybe some advice on why it is causing the problem. Thanks in advance.

1

There are 1 answers

0
Gopi On BEST ANSWER

Segmentation fault because memory is not being allocated to structure LIST

    newmode->next = malloc(sizeof(LIST));