Valgrind tells me I have a leak with malloc'ed node below. However, when I try to free it (free(n);) at the bottom of my code, outside the while loop, the program won't run (it doesn't pass check50 anymore).
When I try to malloc outside the while loop and free at the end of the program, the program also won't run though it compiles.
Any help is appreciated.
bool load(const char *dictionary)
{
// Open dictionary for reading
FILE *file = fopen(dictionary, "r");
if(!file)
{
return false;
}
node *n = NULL;
char dictionaryword[LENGTH + 1];
while (fscanf(file, "%s", dictionaryword) == 1)
{
n = malloc(sizeof(node));
// Add scanned word to node element
strcpy(n->word, dictionaryword);
// Get hash
int index = hash(&dictionaryword[0]);
// Case one: at least one node in hash table at index
if (table[index] != NULL)
{
node *tmp = table[index];
table[index] = n;
n->next = tmp;
wordcount++;
}
// Case two: no node in hash table at index
// Also add node to beginning of list
if (table[index] == NULL)
{
table[index] = n;
wordcount++;
}
if (n == NULL)
{
free(n);
return false;
}
}
fclose(file);
return true;
}