gpt4 book ai didi

CS50 PSET4 无法释放拼写器中的内存

转载 作者:行者123 更新时间:2023-11-30 16:07:59 24 4
gpt4 key购买 nike

我的代码运行良好,但 valgrind 显示分配给所有节点的内存仍然可以访问。这会导致 check50 的内存泄漏测试失败。这是 valgrind 显示的内容 -

堆摘要:
==14338== 退出时使用:143,091 个 block 中的 8,013,096 字节
==14338== 总堆使用量:143,096 次分配,5 次释放,已分配 8,023,416 字节
在丢失记录 1 of 1 中,仍然可以访问 143,091 个 block 中的 8,013,096 字节

这是我的代码-

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "dictionary.h"

// Represents number of buckets in a hash table
#define N 26

// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;

// Represents a hash table
node *hashtable[N];

//to count no. of words in the dictionary
int count = 0;

// Hashes word to a number between 0 and 25, inclusive, based on its first letter
unsigned int hash(const char *word)
{
return tolower(word[0]) - 'a';
}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
hashtable[i] = NULL;
}

// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}

// Buffer for a word
char word[LENGTH + 1];

// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
// TODO

//create a new node
node *newnode = (node *)malloc(sizeof(node));

//check if new node is allocated memory successsfully
if (newnode == NULL)
{
unload();
return false;
}

//copy word from dictionary to new node
//newnode->word = word; (X) why?
strcpy(newnode->word, word);

//hash the word
int n = hash(word);

//add node to the correct bucket
newnode->next = hashtable[n];
hashtable[n] = newnode;

count++;

}

// Close dictionary
fclose(file);

// Indicate success
return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return count;
}

// Returns true if word is in dictionary else false
bool check(const char *word)
{
// TODO

//hash the word to find its bucket
int n = hash(word);

//traverse through the bucket
node *temp = hashtable[n];
while (temp != NULL)
{
if (strcasecmp(temp->word, word) == 0)
{
return true;
}
temp = temp->next;
}

return false;
}

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// TODO

node *cursor;

for (int i = 0; i > 26; i++)
{
cursor = hashtable[i];
while (cursor != NULL)
{
node *temp = cursor;
cursor = cursor->next;
free(temp);
}
}

return true;
}

最佳答案

在这一行使用带有断点的 debug50 for (int i = 0; i > 26; i++)卸载并逐步执行。刚刚发生了什么???该行有一个错字。将鼠标悬停在下方即可查看剧透。

循环永远不会处理,因为 i初始化为 0 和 i > 26是假的

关于CS50 PSET4 无法释放拼写器中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com