I have a problem to free the memory for the variable lowercaseword, I try to do it above the return statement with free(lowercaseword), but then the program stops working and I get errors on check50. Any idea how I should manage to free it and still have a working hash function?

unsigned int hash(const char *word)
    //Store length of word + place for null character
    int wordlength = strlen(word) + 1;

    //Assign enought memory in a new variable to store the word
    char *lowercaseword = malloc(wordlength);

    //Copy the word constant to variable lowercaseword
    strcpy(lowercaseword, word);

    //Change all characters in lowercaseword to lower case
    for (int i = 0; i < strlen(lowercaseword); i++)
        lowercaseword[i] = tolower(lowercaseword[i]);

    // djb2 hash function from http://www.cse.yorku.ca/~oz/hash.html
    unsigned int hash = 5381;
    int c;

    while ((c = *lowercaseword++))
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    //"Translate" the hash value into the span of the hash-table
    hash = hash % N;

    return hash;

    // TODO
    return 0;

I would recommend forgoing all the overhead of allocating new memory on every call to hash().

Instead, consider just looping through word and replacing c with tolower(word[i]) in your hash calculation.

Edit: as mentioned in another comment, the reason your free() fails is because you use the ++ increment operator to step through lowercaseword. While pointer math is a valid way to access data in memory, the increment operator actually changes the value of lowercaseword permanently, meaning it no longer points to the memory block you want to free().

  • Thank you that worked well and thank you for explaining it, I was puzzled why it didn't work but as you describe it become much clearer! Have a nice weekend.
    – Alexander
    Nov 28 '20 at 19:57

The memory allocated to the lowercaseword pointer that was malloc'd needs to be freed before exiting the function.

The fix is simple. First, copy the address of lowercaseword to another pointer, say tempto save it. Then, Add free(temp); before the return statement.

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

  • 1
    It won't work in this case because he steps through the string by using the increment operator on the pointer, changing the pointer and making it invalid when passed to free().
    – Sentox
    Nov 28 '20 at 19:37
  • Good point. I'll adjust my answer.
    – Cliff B
    Nov 28 '20 at 19:55

You must log in to answer this question.

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