当我使用 free() 释放分配的指针时出现无效指针错误
Error invalid pointer when I use free() to free a malloced pointer
在我的函数中使用了这个指针后,我无法释放它。
它给了我这个错误信息。该函数应检查 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!='[=10=]')
{
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
。
在我的函数中使用了这个指针后,我无法释放它。 它给了我这个错误信息。该函数应检查 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!='[=10=]')
{
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
。