添加函数

时间:2018-05-27 04:04:15

标签: c memory-leaks malloc valgrind trie

我一直试图让我的代码工作。它编译但是当我运行它时我得到一个段错误,gdb和valgrind特别指向这一行,我的问题是我真的不知道如何解决它:

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

在addword()中。 本质上我应该在头文件中实现trie数据结构的功能:makedictionary,add,search和delete。

这是学校提供的头文件:

#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有点新意,所以任何提示都会非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我猜这种混淆在于理解

typedef struct _tnode__ *Dict, TNode;

这意味着

Dict lookup;

相同
TNode* lookup;

所以当你创建字典时

void newdict(Dict* dp)

相同
void newdict(TNode** dp)

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

*dp = malloc (sizeof(TNode));

尝试一下,看看它是否解决了您的问题。