在我的函数中使用它后,我无法释放它。 它给了我这个错误信息。该函数应检查 trie 字典,以确定单词拼写正确还是错误。 root 是第一个 trie 节点。
Error in `./speller': free(): invalid pointer: 0x00007fe53a80d848
函数如下:
bool check(const char *word)
{
int pos=0;
int path;
char wordChar=*(word+pos);
wordTriePtr cursor=(wordTriePtr) malloc(sizeof(wordTrie));
cursor=root;
while(wordChar!='\0')
{
path=determinePath(wordChar);
if(cursor->children[path]==NULL)
{
free(cursor);
return false;
}
else
cursor = cursor->children[path];
wordChar=*(word+(++pos));
}
if(cursor->isThisWord==true)
{
free(cursor);
return true;
}
else
{
free(cursor);
return false;
}
}
我做错了什么?
最佳答案
仔细看看这两行:
wordTriePtr cursor=(wordTriePtr) malloc(sizeof(wordTrie));
cursor=root;
第一个定义变量 cursor
并将其初始化为指向您分配的一些内存。
第二行重新分配变量,使其指向其他地方。
在循环的更下方
cursor = cursor->children[path]
再次重新分配它。
重新分配基本上等同于
int a = 5;
a = 10;
然后想知道为什么 a
不等于 5
。
我的猜测是您根本不应该调用malloc
和free
。
关于c - 当我使用 free() 释放分配的指针时出现无效指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656455/