trie中未初始化的值

时间:2014-03-31 12:50:12

标签: c initialization valgrind trie

我刚刚在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);
}

1 个答案:

答案 0 :(得分:4)

创建start节点时,您将array成员保留为未初始化状态,但稍后在add功能中对其进行操作。这是第一次

current = current->array[word[i] - 'a'];  

我认为以下应解决问题:

trie* start = malloc(sizeof(trie));
for(int i = 0; i < 28; ++i)
{
   start->array[i]=NULL;
}