C编程Trie树堆缓冲区溢出
C programming Trie tree heap buffer overflow
我刚开始编程,有一个问题:我想把大量的词插入到一棵特里树中。然后遍历树并释放所有节点,以便我可以再次插入这些单词。但是当字数很大时(比如 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
函数的 return。如果为 NULL,则表示您已达到此进程的最大堆内存,因此 malloc
无法为您分配额外的内存。
我刚开始编程,有一个问题:我想把大量的词插入到一棵特里树中。然后遍历树并释放所有节点,以便我可以再次插入这些单词。但是当字数很大时(比如 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
函数的 return。如果为 NULL,则表示您已达到此进程的最大堆内存,因此 malloc
无法为您分配额外的内存。