I'm very new to programming and I've been trying to finish the cs50 course without just copying other people's code and trying to understand why mine won't work. I'm currently stuck in pset5 (I have been for a couple of days now), the code compiles ok, but not works and valgrind returns:
Process terminating with default action of signal 11 (SIGSEGV)
==1697== Access not within mapped region at address 0x0
==1697== at 0x401A86: hash (dictionary.c:53)
==1697== by 0x401B71: load (dictionary.c:78)
==1697== by 0x4012BE: main (speller.c:40)
here's my code:
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include "dictionary.h"
/*
** Global variable that indicates the number of words loaded in the dictionary
*/
unsigned int loadedWords = 0;
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 54;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
if (table[hash(word)]->next == NULL)
{
return false;
}
else if (strcasecmp(word, table[hash(word)]->word) == 0)
{
return true;
}
else
{
return check(table[hash(word)]->next->word);
}
}
// Hashes word to a number
unsigned int hash(const char *word)
{
char lowerCaseWord[LENGTH + 1];
for (int i = 0; word[i]; i++)
{
lowerCaseWord[i] = tolower(word[i]);
}
unsigned int hashNumber = ((int)word[0] + (int)word[1]) % 53;
return hashNumber;
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
printf("Could not open
");
return false;
}
char word[LENGTH + 1];
while (fscanf(file, "%s", word) != EOF)
{
node *buffer = malloc(sizeof(node));
if (buffer == NULL)
{
return false;
}
strcpy(buffer->word, word);
buffer->next = table[hash(word)]->next;
table[hash(word)]->next = buffer;
loadedWords ++;
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
return loadedWords;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
for (int i = 0; i < N - 1; i++)
{
while (table[i] != NULL)
{
node *tmp = table[i]->next;
free(table[i]);
table[i] = tmp;
}
}
return true;
}
Could someone please point out why this won't work and/or how to fix this? I'm not looking for the complete solution to the problem, I'd just like to know what my error is or how my logic is wrong. Thanks.
question from:
https://stackoverflow.com/questions/66056805/cs50-speller-compiles-yet-not-runs-at-all 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…