0

Working on the unload function in speller (dictionary.c)...

My current test dictionary simply contains a letter c, as I'm just trying to make sure one iteration will work.

So I should (and do, proved by debug50) have a node at root->children[2]. root-children[2]->is_word is set to true. I callocd my nodes, so all of root-children[2]->children are empty nodes.

I start by making sure root is not NULL and does have children. All good there.

However, whenever I try to set a node to NULL via its variable, it doesn't become NULL. (IE, the variable shows NULL, but root->children[2] is not NULL.)

Here's some example code:

// root is present and has children, so move to its child node
node *traverse_node = root->children[2];

// these print statements show that both representations are NOT NULL
fprintf(stderr, "before setting traverse_node to NULL: %s\n", traverse_node ? "not null" : "is null");
fprintf(stderr, "before setting traverse_node to NULL: %s\n", root->children[2] ? "root->children[2] is not null" : "root->children[2] is null");

// setting the variable to NULL; I expect root->children[2] to become NULL
traverse_node = NULL;

// however, traverse_node shows NULL, root->children[2] does not!
fprintf(stderr, "after setting traverse_node to NULL: %s\n", traverse_node ? "not null" : "is null");
fprintf(stderr, "after setting traverse_node to NULL: %s\n", root->children[2] ? "root->children[2] is not null" : "root->children[2] is null");

return 1;

Here are my results upon makeing and running:

before setting traverse_node to NULL: not null
before setting traverse_node to NULL: root->children[2] is not null
after setting traverse_node to NULL: is null
after setting traverse_node to NULL: root->children[2] is not null

Update for clarification: if I set the node directly, it does become NULL, eg: root->children[2] = NULL works fine.

What am I doing wrong? How do I set the node to NULL within the children array?

1

The simple answer is that you set the child pointer to NULL by setting the child pointer to NULL.

Remember that when you say node *traverse_node you are declaring a pointer that holds an address. You are then storing in that pointer a copy of the address of the root->children[2] node. When you then say traverse_node = NULL`, you are changing the value in traverse_node itself, so that it no longer holds the address of the child node, but NULL instead.

My question though is, why do you want to set the nodes to NULL? When unloading the trie, it's sufficient to simply free the nodes, which makes their memory available to other processes. You don't need to also set them to NULL.

| improve this answer | |
  • I was experimenting and found several references which suggested setting to NULL after free'ing. – leanne Aug 30 '19 at 2:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .