0

after doing "speller" i got a segmentation fault. after using debug50 i managed to find out it was on the last line of the hash function. Can you please help me understand what is the problem? (the hash table has 702 buckets)

unsigned int hash(const char *word)
{
    
    if (sizeof(word) < 2)
    {
        return 27 * ((toupper(word[0]) - 'A'));
    }
    return (26 * (toupper(word[0]) - 'A')) + (toupper(word[1]) - 'A') + 2;
}

Thank you!

1 Answer 1

1

I suspect that it is failing anytime it tries to hash a word with only one letter.

Look carefully at the if statement:

if (sizeof(word) < 2)

What, exactly, is word?

unsigned int hash(const char *word)

It's a pointer! The variable word is a pointer that contains the address of the string, not a var that contains the string directly. That means that the if statement is checking the sizeofI( [a pointer] ), which is always the same and always greater than 2 for modern architectures.

So, the code fails anytime it is checking a string with only one character. The second "letter" would be the end of string marker, or 0x00. This produces a bad result (probably a negative number) when the code executes. You can try working it out on paper. Try calculating the result for "a". It should be -63, I think.

Now, if the code were to check for strlen() instead of sizeof(), it might just work. ;-)

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 .