Given the structure shown, you are allocating insufficient memory and copying to an uninitialized pointer. Both are dangerous.
You need something more like:
node *create(char name[]){
node *temp = malloc(sizeof(*temp));
if (temp == NULL)
return NULL;
temp->data = malloc(strlen(name) + 1);
if (temp->data == NULL)
{
free(temp);
return NULL;
}
strcpy(temp->data, name);
temp->left = temp->right = NULL;
// temp->generation = 0; // removed from revised question
return temp;
}
Consider whether you can use strdup()
to allocate a copy (duplicate) of the string. You'd still need to check that was successful. Note that freeing a node
involves two calls to free()
. Also, the calling code needs to check whether the node was successfully allocated. However, this code imposes no error handling strategy on its caller — the calling code can do what it likes as long as it doesn't try to dereference a null pointer returned by the code.
Alternatively, you could use a C99 'flexible array member' like this:
typedef struct BST {
struct BST *left;
struct BST *right;
char data[];
} node;
node *create(char name[]){
node *temp = malloc(sizeof(*temp) + strlen(name) + 1);
if (temp == NULL)
return NULL;
strcpy(temp->data, name);
temp->left = temp->right = NULL;
// temp->generation = 0; // removed from revised question
return temp;
}
Now you can free the structure with a single free()
call. However, you can't create an array of these structures (though you could have an array of pointers to such structures). In the context of a tree, that's unlikely to be a problem.