I'm trying to improve my hash function in Speller and I'm having trouble freeing allocated memmory.

I'm getting * Error in `./speller': free(): invalid pointer: 0x0000000001a02252 * Aborted

I know it has something to do with declaring string *str as a global variable but I dont really get it. And I couldnt find help anywhere else.

unsigned int hash(const char *word)
    // malloc space for a word and test it
    char *str = (char*)malloc(46);
    if (str == NULL)
        return false;
    strcpy(str, word);

    // lowercase everything
    for(int i = 0; str[i]; i++)
        str[i] = tolower(str[i]);

    // hash function djb2 by dan bernstein
    unsigned long hash = 5381;
    int c;
    while ((c = *str++))
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    // free alocated memmory

    // return hash number
    return hash % N;

str++ will increment str. So the thing you later try to free is pointing to the first byte behind the string's null terminator, while you are meant to call free for the first byte of the range, the exact pointer malloc returned.

Keep a copy, and modify one copy in the while loop, while you free the other, non-modified one later. There are more options, like using an index (slightly less efficient).

But... I'd rather not do the lower-casing in the hash function. If you do it in check, you can reuse it when calling strcmp and don't have to use strcmpi (which is slower than its more primitive strcmp cousin). If you don't need that variable for the lower-cased copy, the whole thing of malloc/free in the hash function suddenly vanishes, and with it your problem. There wouldn't even be a need for another char* variable. Note that it's const char* word, which doesn't mean word itself is immutable, only that it points to immutable characters.

You must log in to answer this question.

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