I just implemented a trie in c, ran valgrind on my program and although all heaps were freed, it says something about uninitialized values. Here's Valgrind's output http://pastebin.com/7hSWGiDk
And here is trie code(In the trie's typedef, the array has 26 elements for English letters, 1 element for apostrophe and 1 element which when not null, marks the end of word) :
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct trie
{
struct trie* array[28];
} trie;
void add(char* word, trie* start)
{
trie* current = start;
trie* previous = NULL;
int i = 0;
while(current!=NULL && i < strlen(word))
{
previous = current;
current = current->array[word[i] - 'a'];
i++;
}
i--;
for(;i < strlen(word);i++)
{
previous->array[word[i] - 'a'] = malloc(sizeof(trie));
previous = previous->array[word[i] - 'a'];
}
previous->array[27] = malloc(sizeof(trie));
}
bool search(char* word, trie* start)
{
trie* current = start;
for(int i = 0;i < strlen(word);i++)
{
current = current->array[*(word+i) - 'a'];
if(current == NULL)
{
return false;
}
}
if(current->array[27]!=NULL)
{
return true;
}
return false;
}
void clear(trie* start)
{
if(start != NULL)
{
for(int i = 0;i < 28;i++)
{
clear(start->array[i]);
}
free(start);
}
}
int main(void)
{
trie* start = malloc(sizeof(trie));
char* word = "ba\0";
add(word,start);
clear(start);
}
When you create start
node you leave array
members uninitialized , but later in add
function you operate on them. For the first time in this line
current = current->array[word[i] - 'a'];
I think following should solve the issue :
trie* start = malloc(sizeof(trie));
for(int i = 0; i < 28; ++i)
{
start->array[i]=NULL;
}