I thought it was a good idea to write a function to create a new node because it seemed to come up more than once. I named it new_node()
and it looks like this:
struct node *new_node(void)
{
node *new_node = malloc(sizeof(node));
new_node->is_word = false;
for (int i = 0; i < 27; i++)
{
new_node->branch[i] = NULL;
}
return new_node;
}
I removed checking for NULL from within the function because it generated an error as return 1;
is an int and I currently have new_node()
returning a struct node.
I can't figure out what I'm missing because the side effect is I'm checking for NULL both before and after I call new_node()
. Here's the excerpt:
// loop to read char from file one at a time
for (int c = fgetc(fp_dictionary); c != EOF; c = fgetc(fp_dictionary))
{
// for chars which are not a new line
if (c != '\n')
{
// calls alpha function to convert decimal to alphabetic index
alpha(&c);
// checks if root node's branch ptr at alpha index is NULL
// 'root' is dynamically declared on the heap and therefore, uses -> to dereference
if (trav->branch[c] == NULL)
{
// creates new node if ptr at index c is NULL
trav->branch[c] = new_node();
// quits if ptr returned for new_node is NULL
if (trav->branch[c] == NULL)
{
return 1;
}
// advance in trie to be ready for next char
trav = trav->branch[c];
}
else if (trav->branch[c] != NULL)
{
// move to existing node and continue
trav = trav->branch[c];
}
}
I have been made aware of calloc, but as it can return NULL, it doesn't seem to get me out of this. Am I interpreting the man page wrong? I'd be so happy if it were the case. I considered when trav
was assigned the value of trav = trav->branch[c];
, the loop took care of the NULL check, but it never exits the program if it were to come back true. Is this an issue or no? I feel as though I've blown something simple out of proportion. Thanks for the help.