[英]Uninitialized values in trie
I just implemented a trie in c, ran valgrind on my program and although all heaps were freed, it says something about uninitialized values. 我刚刚在c中实现了trie,在程序上运行了valgrind,尽管所有堆都已释放,但它说明了一些未初始化的值。 Here's Valgrind's output http://pastebin.com/7hSWGiDk
这是Valgrind的输出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) : 这是trie代码(在trie的typedef中,该数组包含26个英文字母元素,1个单引号元素和1个不为null时表示单词结尾的元素):
#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. 创建
start
节点时,将array
成员保留为未初始化状态,但稍后在add
函数add
进行操作。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.