C编程Trie树堆缓冲区溢出

C编程Trie树堆缓冲区溢出,c,memory,tree,trie,C,Memory,Tree,Trie,我刚开始编程,有一个问题:我想在trie树中插入大量单词。然后遍历树并释放所有节点,以便我可以再次插入这些单词。但是当字数较大(比如100万)时,我遇到了堆缓冲区溢出,这些函数适用于字数较少的情况: 这里是节点 struct node { struct node * parent; int noempty; int isword; int super; int occurrence; int leaf; struct node * chil

我刚开始编程,有一个问题:我想在trie树中插入大量单词。然后遍历树并释放所有节点,以便我可以再次插入这些单词。但是当字数较大(比如100万)时,我遇到了堆缓冲区溢出,这些函数适用于字数较少的情况:

这里是节点

struct node
{
    struct node * parent;
    int noempty;
    int isword;
    int super;
    int occurrence;
    int leaf;
    struct node * child[26];
};

要插入的函数:

struct node* insert(struct node *root,char *c)
{
    int i=0;
    struct node *temp=root;
    int l=length(c);
    while(i!=l)
    {
        int index=c[i]-'a';
        if(temp->child[index]==NULL)
        {
            //New Node
            struct node *n=malloc(sizeof(struct node)); 
            n->parent=temp;
            temp->child[index]=n;
            temp->noempty=1;
        }
        //Node Exist
        if(i!=l&&temp->leaf==1)
        { 
            temp->leaf=0;
        }
        temp=temp->child[index];
        i++;
    }
    if(temp->noempty==0)
    {
        temp->leaf=1;
    }
    temp->isword=1;
    return root;
};

和自由功能:

void freetree(struct node* curs)
{ 
    int i;
    if(!curs) 
        return;  
    for (i = 0; i !=26; i++)
        freetree(curs->child[i]);
    free(curs);
}

谢谢大家!

检查
malloc
函数是否返回。如果为空,则表示您已达到此进程的堆内存最大值,因此
malloc
无法为您分配额外内存。

那么我应该如何代替malloc?如果
malloc
无法分配额外内存,这意味着你不能以不同的方式分配内存。对于这段代码,这也意味着你有一个严重的错误,即使你正在构建一个32位的应用程序,并且只限于2GB的地址空间。你不应该接近任何极限。也许您正试图分配一个负大小的数组。或者你在无限循环中分配节点。这很奇怪,因为我每次都释放了树,它可以处理更少的字。我的建议是使用调试器来确定分配失败时分配的是什么。你释放了26个节点,但不清楚它们是否分配了内存(或者是
NULL
指针)。因此我需要检查循环
while(I!=l)中“freetree(curs->child[I]);”之前的“curs->child[I]==NULL”
既不更新
i
也不更新
l
:这是一个调用
malloc
的无限循环,其返回值未被检查。亲爱的OP,堆大小是有限的,在
10MB
空间大小中有一百万字,可能超过堆的大小。@WeatherVane
i++
在while循环的末尾。我已经编辑了这个问题以获得更好的缩进…等待批准。