c - 当我使用 free() 释放分配的指针时出现无效指针错误

标签 c pointers 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!='\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

我的猜测是您根本不应该调用mallocfree

关于c - 当我使用 free() 释放分配的指针时出现无效指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656455/

相关文章:

c - C中的二维字符数组初始化

c - 在处理 C 中的指针时无法理解代码的输出

macos - Valgrind 支持 Mac OS 10.8 吗?

c++ - 循环中的文件不能被读取超过 17 次

c++ - 为什么这段代码的输出总是一样的?

c - 获取被调用函数C的行号

c - 如何用特定的整数值替换字符串中的字母?

C - 使用 malloc 为结构赋值不起作用

c - 在 Linux 上连接硬件安全模块

c++ - 如何指定指向数组元素的成员指针?