【发布时间】:2020-04-17 11:39:22
【问题描述】:
bool check(const char *word)
{
int length = strlen(word);
//malloc size of char times length of word plus \0
char *lower_case = malloc(sizeof(char) * (length + 1));
lower_case[length + 1] = '\0';
//change characters to lowercase
for (int i = 0; i < length; i++)
{
lower_case[i] = tolower(word[i]);
}
//generate int hash
int index = generate_hash(lower_case);
node_ptr trav = hashtable[index];
while (trav != NULL)
{
if (strcmp(trav->word, lower_case) == 0)
{
return true;
}
trav = trav -> next;
}
free(lower_case);
return false;
}
我从 Valgrind 测试中泄漏了 27 字节的内存;如何释放它?
【问题讨论】:
-
如果您发布 minimal reproducible example 可能会有所帮助,因为您的代码中可能存在其他泄漏/问题。但是对于泄漏,您可以在
return true;之前执行free(lower_case);。 -
如果您有来自 Valgrind 的问题报告,请在问题中包含问题报告。您没有提到 Valgrind 抱怨内存访问越界,但它确实抱怨。正如其他人已经指出的那样,您还需要创建一个 MCVE (Minimal, Complete, Verifiable Example)(或 MRE 或 SO 现在使用的任何名称)或 SSCCE (Short, Self-Contained, Correct Example)。
-
样式指南:点
.和箭头->运算符绑定非常紧密,因为它们是 postfix operators。它们的周围不应有空格。写trav -> next不是惯用的 C 语言,表示编码器是 tyro(新手)。使用trav->next。