Search code examples
carraysnulltrie

How to set all the children to NULL in the trie


I am trying to implement a trie in C. My code compiles correctly, but when I run it with valgrind it shows an error. here is the problematic part:

typedef struct node {
bool end;
struct node *chil[26];
} NODE;
int main()
{
   NODE* ne = (NODE*)malloc(sizeof(NODE)); 
   if(ne->chil[1] == NULL) printf("\nzwycięstwo!\n"); 
   free(ne);
   return 0;
}

and here is the error report:

==3346== Conditional jump or move depends on uninitialised value(s)

==3346== at 0x40076B: main (exp.c:21)

==3346== Uninitialised value was created by a heap allocation

==3346== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64->linux.so)

==3346== by 0x40075A: main (exp.c:20)`

I guess I have to explicitly say that

ne->chill = {NULL};

but this results in compiler error "expected expression"

What should I do? Can I avoid going through the whole array to set pointers to NULL?


Solution

  • A loop is the only way to set all the pointers portably to a NULL value

    for (int i = 0; i < 26; ++i)
      ne->chil[i] = NULL;
    

    You may hear suggestions to use calloc or memset. But a zero-bit pattern is not necessarily the same as a NULL value for a pointer. Even if many platforms implement it that way.