If i run it in another smaller program it works fine( returns the key correct) but on the pset 5 speller it gives segmentation fault. why?
1 Answer
This hash function can return any number from 0 to 17,575, assuming I did my math right. That doesn't account for results when words are less than 3 letters, as @DinoCoderSaurus points out.
What's the size of the array that holds the starting address of each linked list? Is it smaller than 17575? If it is, then that means that the hash function can return values outside of the valid range of the array. That may or may not produce a seg fault. If it doesn't, that's actually worse because it'll lead to unpredictable results.
There needs to be some kind of limit applied to the value being returned by the hash function. Usually, this is done by applying the modulo function with the range of the array that this is used as an index for.
To clarify, it looks like this:
return hashvalue % LIMIT ;
Of course, without seeing how the hash value is used in context, this is just an educated guess.
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)
-
"Is it smaller than 17575? If it is, then that means that the hash function can return values outside of the valid range of the array." size of the array is 17576? so i dont think that might be the problem. Commented Feb 16, 2023 at 7:39
-
In that case, we'd need to see the rest of the code to test it.– Cliff BCommented Feb 16, 2023 at 19:50
word+1
fail on 1 and 2 letter words? It may not in a smaller program because of the way memory is allocated and used. That's how memory violations are. What doesvalgrind
report about the smaller program? This hash function cannot be tested because it is pasted as an image and not as text