我正在尝试将主要结构的trigal_node初始化为trie的头,并遇到内存分配问题

问题描述 投票:0回答:1

基本上,当我尝试在main中初始化它时,我是从valgrind获得的

==4262==    at 0x109730: main (in /home/raf/os/domaci4/main)
==4262==  Address 0x544c210 is 0 bytes after a block of size 464 alloc'd
==4262==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4262==    by 0x1096D3: main (in /home/raf/os/domaci4/main)
==4262== 
``` ```

typedef struct trie_node
{
    char c;
    int term;
    int subwords;
    struct trie_node *parent;
    struct trie_node *children[LETTERS];
}trie_node;

这是我如何将其写成全球性的 struct trie_node *head;

在这里,我尝试分配内存并将所有内容设置为0。

    head = (trie_node*) malloc(sizeof(struct trie_node));
    head->term = 0;
    head->parent = NULL;
    head->subwords = 0;
    head->c = NULL;
    int i;
    for(i = 0; i < MAX_WORD_LEN; i++)
    {
        head->children[i] = NULL;
    }

我正试图找出问题所在。任何帮助将不胜感激!

c struct malloc
1个回答
0
投票

您的代码片段没有真正问题的详细信息。

但是,这里有一些我惯用的代码。它应该为您提供一些有关如何修复代码的想法:

#include <stdlib.h>

#define LETTERS     26
typedef struct node node_t;
struct node {
    int let;                                // letter
    int eow;                                // 1=end-of-word

    node_t *parent;
    node_t *child[LETTERS];
};

// triefind -- find matching child node based on id
node_t *
triefind(node_t *par,int let)
{
    int cldidx;
    node_t *cld;
    node_t *match;

    match = NULL;

    for (cldidx = 0;  cldidx < LETTERS;  ++cldidx) {
        cld = par->child[cldidx];

        // skip empty slot
        // NOTE: this will probably never happen based on trieattach
        if (cld == NULL)
            continue;

        if (cld->let == let) {
            match = cld;
            break;
        }
    }

    return match;
}

// trienew -- get new node
node_t *
trienew(int let)
{
    node_t *node;

    node = calloc(1,sizeof(node_t));
    node->let = let;

    return node;
}

// trieattach -- attach new child node
node_t *
trieattach(node_t *par,int let)
{
    node_t *cld;

    // allocate new node
    cld = trienew(let);

    // cross-link parent and child
    cld->parent = par;
    par->child[let] = cld;

    return cld;
}

// triefindx -- find matching child node (create new node if none found)
node_t *
triefindx(node_t *par,int let)
{
    node_t *cld;

    // find existing node
    cld = triefind(par,let);

    // create new node if it doesn't already exist
    if (cld == NULL)
        cld = trieattach(par,let);

    return cld;
}
© www.soinside.com 2019 - 2024. All rights reserved.