How can I correctly initialize a red black tree in C?
Structure:
typedef struct Node{
int key;
struct Node *left;
struct Node *right;
struct Node *parent;
enum {RED, BLACK} color;
}node;
typedef struct RBtree{
struct Node *root;
struct Node *nil;
}rbtree;
Main Function:
int main(){
rbtree *tree;
init_rbtree(&tree);
}
Init Function:
void init_rbtree(rbtree **t){
(*t)->root = NULL;
node *n = (node*)malloc(sizeof(node));
if(n != NULL){
n->color = BLACK;
(*t)->nil = n;
}
}
The program crashes as soon as I run this code.
You need to allocate memory for *t
before you can use it.
void init_rbtree(rbtree **t) {
*t=malloc(sizeof(rbtree));
if (*t==NULL) {
//handle error
}
else {
(*t)->root = NULL;
node *n = malloc(sizeof(node));
if(n != NULL){
n->color = BLACK;
(*t)->nil = n;
}
}
}