简体   繁体   中英

C programming Trie tree heap buffer overflow

I just started programming and have a question: I want to insert a large amount of words into a trie tree. Then traverse the tree and free all the nodes so that I can insert these words again. But when the number of words is large (say 1 million), I hit a heap buffer overflow, these function works for smaller amount of words:

Here is the nodes

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


The function to insert:

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;
};


And the free function:

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

Thank you!

Check for the return of the malloc function. If it is NULL, it means you have reached the maximum of your heap memory for this process, and thus malloc cannot allocate extra memory for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM