0
unsigned int
hash(const char *str)
{
    unsigned int hash = 5381;
    int c;
    int i;
    size_t k= strlen(str)*1;
    char *str2=malloc(k+1);
    strcpy(str2,str);

    for(i=0;i<strlen(str);i++)
    {
        if(isalpha(str[i]))
            str2[i]=tolower(str2[i]);
    }

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

    free(str2);
    return hash%143090;
}

This is the Djb2 hash function with a slight modification for case insensitivity. Valgrind shows the error "Invalid write of size 1" at strcpy.

1 Answer 1

1

I assume you have created str2 for the case insensitivity. No memory has been allocated to it, therefore anytime you write to it (as with strcpy), there will be an "invalid write". (And if you allocate it, you must set it free!:).

Since you are not the author of the hash function, considered "correct casing" the word in your code before sending it to the function. Then you don't have to debug code you didn't create.

4
  • I "malloc"d str2 as you told. But now, I'm getting invalid pointer seg error at free. Why is that?
    – Vaish MK
    Commented Feb 16, 2017 at 15:51
  • I wouldn't mess with someone else's function. I would send the word to function already lower-cased. Commented Feb 16, 2017 at 16:33
  • That was the simplest solution. Why didn't I think of that? Thanks! Just fun, bug in my mind, can you tell me why compiler gives invalid pointer at free() leading to seg fault? I can't get it out of my head
    – Vaish MK
    Commented Feb 16, 2017 at 16:47
  • Because this *str2++ is "pushing the pointer" and the while loop ends when str2 is the next address after the word, so it's trying to free memory it doesn't own. Commented Feb 16, 2017 at 17:37

You must log in to answer this question.

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