In my attempt at pset 5's speller I'm trying to free the last memory leak and running into the two same errors.

If I don't free the cursor after freeing all the nodes then:

Looks like your program leaked 96 bytes of memory. Did you forget to free memory that you allocated via malloc? Take a closer look at line 46 of dictionary.c.

If I free the cursor then I am told:

Looks like you're trying to access 8 bytes of memory that isn't yours? Did you try to index into an array beyond its bounds? Take a closer look at line 139 of dictionary.c.

Here is my unload attempt:

bool unload(void)
// run the cursor along the hashtable, freeing any memory
for (int i = 0; i < SIZE; i++)
    node* cursor = hashtable[i];

    while (cursor != NULL)
        node* temp = cursor;
        cursor = cursor->next;
    hashtable[i] = NULL;
loaded = false;
return true;

If for freeing the cursor I just add the line "free(cursor);" after free temp.

Line 46 is the check part of speller:

bool check(const char* word)
// allocates memory for the checker
node* checker = malloc(sizeof(node));
char* lower = malloc((LENGTH+1) * sizeof(char));
int length = strlen(word);
for (int i = 0; i < length; i++)
    lower[i] = tolower(word[i]);

// hashes the word for indexing
int index = hash(word);

// the point where the word is in the checker
checker = hashtable[index];

// loops through the nodes until the node list terminates
while (checker != NULL)
    if (strcmp(checker->word, lower) == 0)
        return true;
    checker = checker->next;

return false;

I'd be oh so grateful if someone could explain whats wrong/what I'm not seeing properly so I can fix the problem.


The unload function looks ok.

The check function has two definite memory leaks. Every time check is called, two mallocs are executed. Neither of them are freed before the check function terminates.

With checker, the malloc is unnecessary. checker is reassigned later (thus losing the address of the malloc'd memory and causing the leak) and could simply be assigned null.

node* checker = NULL;

Just because a pointer is created, memory doesn't have to be assigned to it. This is a perfect example.

lower could be done as a char array instead of malloc'd memory, solving that problem completely.

If there are additional issues (I suspect there are), it would be necessary to have the entire code to test. Memory leak problems may be identified on a given line but have their cause in a completely different area. For instance, memory leaks in load can manifest in unload, or vice versa.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .