add 函数中的 C trie 内存泄漏

标签 c memory-leaks malloc valgrind trie

我一直在努力让我的代码正常工作。它可以编译,但是当我运行它时,我得到一个段错误,gdb 和 valgrind 特别指向这一行,我的问题是我真的不知道如何修复它:

    if (!pCrawl->cvec[index]) {

它在addword()中。 本质上,我应该在头文件中实现 trie 数据结构的函数:makedictionary、添加、搜索和删除。

这是学校提供的头文件:

#define VECSIZE ('z'-'a' + 1)

typedef char *word;
enum __bool__ { FALSE, TRUE };
typedef enum __bool__ bool;

typedef struct __tnode__  *Dict, TNode;

struct __tnode__ {
  Dict cvec[VECSIZE];          
  bool eow;                   
};

void newdict(Dict *dp);
void addword (const Dict r, const word w);
bool checkword (const Dict r, const word w);
void delword (const Dict r, const word w);

void barf(char *s);           

也不是因为我无法更改头文件,并且 bool 是一个 typedef,所以我无法使用 stdbool.h。 这是我正在编写的 C 代码:

#define CHAR_TO_INDEX(c) ((int)c - (int)'a')

void newdict (Dict *dp) {
    *dp = NULL;
    dp = (Dict *)malloc(sizeof(Dict));
    if (dp) {
        int i;
        (*dp)->eow = FALSE;
        for (i = 0; i < VECSIZE; i++) {
            (*dp)->cvec[i] = NULL;
        }
    }
}

void addword (const Dict r, const word w) {
    int level;
    int length = strlen(w);
    int index;

    Dict pCrawl = r;
    printf("line 1\n");
    for (level = 0; level < length; level++) {
        index = CHAR_TO_INDEX(w[level]);
        if (!pCrawl->cvec[index]) {
            newdict(&(pCrawl->cvec[index]));
        }
        pCrawl = pCrawl->cvec[index];
    }
    pCrawl->eow = TRUE;
}

bool checkword (const Dict r, const word w) {
    int level;
    int length = strlen(w);
    int index;

    Dict pCrawl = r;

    for (level = 0; level < length; level++) {
        index = CHAR_TO_INDEX(w[level]);
        if (!pCrawl->cvec[index]) {
            return FALSE;
        }
        pCrawl = pCrawl->cvec[index];       
    }
    if (pCrawl != NULL && pCrawl->eow) {
        return TRUE;
    } else {
        return FALSE;
    }
}

我对 C 有点陌生,所以任何提示将不胜感激。提前致谢。

最佳答案

我猜困惑在于理解

typedef struct _tnode__ *Dict, TNode;

这意味着

Dict lookup;

相同
TNode* lookup;

所以当你创建字典时

void newdict(Dict* dp)

与相同

void newdict(TNode** dp)

因此,在分配时,分配 sizeof(Dict) 与 sizeof(TNode*) 相同,即 sizeof 指针。真正需要的是一个TNode。注意 - 在 C 中,不需要强制转换 malloc。仅 C++ 需要它。

*dp = malloc (sizeof(TNode));

尝试一下,看看是否可以解决您的问题。

关于add 函数中的 C trie 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50548917/

相关文章:

c - 拆分字符串中的空格并将它们存储在没有库的C中的表中

C奇怪的int数组指针

c - 当我处理信号_handler和主函数中的变量时,如何屏蔽信号

c - 如何使用 C(不是 C++)在结构的所有实例中拥有一个 const 成员?

c - 需要为 2D 元组数组和未知大小的 2D 指针数组分配内存?

java - 黑莓 7 : Odd Memory Leak in Root Process

ios - 如何避免 subview Controller 的内存泄漏

c - C 中的浮点表示

c - C编程:如何检查输入字符串是否包含大写和小写字母的组合

c - 当循环在 C 中重复超过 127 次时发生内存泄漏