I have been trying to solver spell checker but my program crashes with a segmentation fault.
Valgrind gives me the following errors: https://codeshare.io/5Ddk6m
Here's my code: https://codeshare.io/21jgXB
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.Sign up to join this community
Okey, when looking at Valgrind you should look for the word SIGSEGV first. In this case you are getting:
==10415== Process terminating with default action of signal 11 (SIGSEGV) ==10415== Access not within mapped region at address 0x8005FF280 ==10415== at 0x40126C: load (dictionary.c:92) ==10415== by 0x4009B4: main (speller.c:40)
This is telling you that in dictionary.c, line 92 you are accessing something that is not mapped, which normally is because you access something beyond it's index (imagine an array of length 3 and you are trying to access array).
This is line 92 in dictionary.c:
So you are accessing table beyond it's possible index. Now, if you think about it, the problem is then that you are not creating a big enough hashtable (when setting the value of N) or hash() is not working as intended.
There are different solutions you could try. I think the easiest one is to have hash() return values not greater than N. How could you do this? Well, this is a tip that is given on the instructions of the problem set: by using
return x % N
in hash (x being the number you would originaly return) you can make sure it is within the wanted values. I'll let you think about why.
That should solve this issue. Now, valgrind also says
==10415== 1,667,904 bytes in 29,784 blocks are still reachable in loss record 2 of 2 ==10415== at 0x4C31B25: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==10415== by 0x401222: load (dictionary.c:88) ==10415== by 0x4009B4: main (speller.c:40)
which means the memory you allocated in line 88 is not being correctly freed. This might be due to the previous error or it might not. If it isn't there's probably a problem in unload, so in that case make sure to check that out. Hope it helps, good luck!