0

指向泄漏内存的函数的链接。

bool check(const char* word)
{

    uint32_t len = strlen(word);
    char currentWord[len+1];

    for(int k = 0; k <= len; k++)
    {
        currentWord[k] = tolower((char)word[k]);
    }

    bool wordPresent = false;
    uint32_t indexSize = (dict.wordCount / ITEMSPERBUCKET);
    uint32_t index = (hashFunction(currentWord)%(indexSize-1));

    dictNode *temp = malloc(sizeof(dictNode));
    temp = chainedHashTable[index];
    do
    {
        if (strncmp(temp->word, currentWord, temp->len) == 0)
        {
            wordPresent = true;
            temp = NULL;
        }
        else
        {
            temp = temp->next;
        }
    }
    while (temp != NULL);

    free(temp);
    return wordPresent;
}

http://codepad.org/G8uuS79s

任何帮助将不胜感激。

4

2 回答 2

4

在分配它之后,你在下一行失去了 malloc 的值temp......你没有得到free()之后的值。

此外,当您最终退出while循环并在调用之前free(),temp == NULL。

于 2013-04-15T18:43:17.080 回答
4

直接在你之后malloc

dictNode *temp = malloc(sizeof(dictNode));
temp = chainedHashTable[index];

您用 . 覆盖malloced 内存的地址chainedHashTable[index]。因此,您丢失了malloced 内存的唯一句柄,并泄漏了它。

幸运的是,你正在释放的东西

while (temp != NULL);

free(temp);

是一个空指针,并且freeing 是无害的。free chainedHashTable[index]例如,如果您尝试这样做,那可能会破坏您的程序。

于 2013-04-15T18:43:22.713 回答