【问题标题】:Uninitialized values in trietrie中未初始化的值
【发布时间】: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


    【解决方案1】:

    当您创建 start 节点时,您会留下 array 成员 uninitialized ,但稍后在 add 函数中您对它们进行操作。第一次在这一行

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

    我认为以下应该可以解决问题:

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

    【讨论】:

    • 或者干脆用 calloc() 代替 malloc
    • @Claptrap No no 不要使用 calloc 来初始化指针,不能保证空指针被表示为所有位为零
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2017-10-30
    • 2021-04-11
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多