【发布时间】:2021-08-11 08:44:07
【问题描述】:
我刚刚完成了 cs50 的 pset5,其中一个函数旨在将字典的内容加载到哈希表中。在所述函数的循环内,我必须为一个节点分配内存,稍后我将分配给哈希表中的节点。
当我尝试在每次循环迭代后释放节点 n 时,我的函数将不起作用。 当我不释放它时,它确实可以工作,更令人困惑的是,它还通过了 valgrind 检查和 cs50 的内存泄漏检查。
我的问题是:
-
我将如何释放“节点 n”以允许我的功能仍然工作?
-
当我不释放 'n' 时,为什么 valgrind 没有检测到任何内存泄漏?它是未定义行为的示例吗?
-
循环中的 malloc 是如何工作的,它是每次分配新的内存块还是覆盖之前的内存块?
任何答案将不胜感激。
代码如下:
bool load(const char *dictionary)
{
//Setting counter to determine wheather node comes second in linked list or not.
int counter = 0;
//declaring string array to store words from dictionary
char word1[LENGTH +1];
FILE *dic = fopen(dictionary, "r");
if(dic == NULL)
{
return false;
}
//Loop loading words from dictionary to hash table
while(fscanf(dic, "%s", word1) != EOF )
{
node *n = malloc(sizeof(node));
if (n == NULL)
{
return false;
free(n);
}
int i = hash(word1);
//Storing word in temporary node
strcpy(n->word, word1);
n->next = NULL;
//Three different conditions(first node of[i], second node of[i], and after second node of[i])
if(table[i] == NULL)
{
table[i] = n;
counter++;
counter2++;
}
else if (counter == 1)
{
table[i]->next = n;
counter = 0;
counter2++;
}
else
{
n->next = table[i];
table[i] = n;
counter2++;
}
}
fclose(dic);
return true;
【问题讨论】: