我是否在内部或外部调用函数中为特里分配内存?

时间:2018-09-17 04:27:20

标签: c memory-management data-structures cs50

我正在用C实现大型字典中单词的trie数据结构。字典包含以下格式的字符串:

abacus
babble
cabal
....

我在load函数之外为trie定义并分配了内存。 load从字典中读取每个单词,并将每个字符插入每个children[27]内部的数组node的位置。索引0到25表示字符az和撇号字符'在位置26。

问题是我不知道该为调用函数内部还是外部的trie顶层创建并分配内存。使用完Trie后,将使用另一个功能unload释放内存。我无法修改main函数,所以不确定完成后是否不会发生内存泄漏。

代码如下:

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// trie data structure for 26 letters and apostrophe
typedef struct node
{
    bool is_word;
    struct node *children[27];
} node;

// allocate memory for trie top level and set them to 0
node *root = calloc(1, sizeof(node));

// loads dictionary into memory, return true if successful
bool load(const char *dictionary)
{
    // open input file
    FILE *fp = fopen(dictionary, "r");
    if (fp == NULL)
        return false;

    int p;    // trie index position
    char c;   // current char

    // scan dictionary word by word
    while (fscanf(fp, "%s", word) != EOF)
    {
        // set head pointer to point to root
        node *head = root;

        // loop through current word
        for (int i = 0; i < strlen(word); i++)
        {
            c = word[i];

            // ASCII to alphabet position, apostrophe last index
            if (isalpha(c))
                p = c - 'a';
            else if (c == '\'')
                p = 26;

            // allocate memory and point head to new node
            if (head->children[p] == NULL)
            {
                head->children[p] = calloc(1, sizeof(node));
                head = head->children[p];
            }
            // otherwise point head to children
            else if (head->children[p] != NULL)
                head = head->children[p];
        }
        // complete word, set flag to true
        head->is_word = true;
    }
    // finished
    fclose(fp);
    return true;
}

0 个答案:

没有答案