【发布时间】:2014-03-31 12:50:11
【问题描述】:
我刚刚在 c 中实现了一个 trie,在我的程序上运行了 valgrind,虽然所有堆都被释放,但它说明了一些关于未初始化值的信息。这是 Valgrind 的输出http://pastebin.com/7hSWGiDk
这里是 trie 代码(在 trie 的 typedef 中,数组有 26 个英文字母元素,1 个撇号元素和 1 个元素,当不为空时,标记单词的结尾):
#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);
}
【问题讨论】:
标签: c initialization valgrind trie