я пытаюсь решить speller, и я хорошо справился с логикой, но у меня есть некоторые утечки памяти, и я не понимаю, откуда она взялась
вот мои реализованные функции
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
node *hashtable[N];
unsigned int words = 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)
{
node *new_node = malloc(sizeof(node));
if (!new_node)
{
unload();
return false;
}
strcpy(new_node -> word, word);
int x = hash(new_node -> word);
if (hashtable[x] == NULL)
{
hashtable[x] = new_node;
hashtable[x] -> next = NULL;
}
else
{
hashtable[x] -> next = new_node;
new_node = hashtable[x];
}
words ++;
}
// 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)
{
if (words > 0)
{
return words;
}
return 0;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int k = hash(word);
if (hashtable[k] == NULL)
{
return false;
}
else
{
for (node *ptr = hashtable[k]; ptr != NULL; ptr = ptr -> next)
{
if (strcasecmp(ptr -> word, word) == 0)
{
return true;
}
}
}
return false;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
int index = 0;
// iterate through entire hashtable array
while (index < N)
{
// if hashtable is empty at index, go to next index
if (hashtable[index] == NULL)
{
index++;
}
// if hashtable is not empty, iterate through nodes and start freeing
else
{
while (hashtable[index] != NULL)
{
node *cursor = hashtable[index];
hashtable[index] = cursor->next;
free(cursor);
}
// once hashtable is empty at index, go to next index
index++;
}
}
// return true if successful
return true;
}
и это результат help50 valgrind Похоже, ваша программа утекла 8 010 184 байт памяти. Вы забыли освободить память, выделенную через malloc? Посмотрите внимательнее на строку 56 словаря.c.
строка 56 - node* new_node = malloc(sizeof(node));
заранее спасибо!