Reputation: 65
I am currently working on pset5 from cs50.
My entire program compiles successfully but stops in the middle of the function called load
when program is executed.
Below is my load
function, and you can see the comment where it gave me a segmentation fault
error.
If you can help me with figuring out how I should approach my error, please do let me know.
I understand that segmentation fault
is caused when the program attempts to access a memory that does not belong to it.
However, I have allocated memory and checked whether there was enough memory to continue on the program.
I will provide comments to highlight what my code does.
// In another header file, I have defined 'LENGTH'
// Maximum length for a word
// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
#define LENGTH 45
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Hash table
// I have initialized the array of `node` pointer to point `NULL`
node *table[N] = {NULL};
unsigned int word_counter = 0;
bool load(const char *dictionary)
{
// Open file, and if cannot open, return false
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
return false;
}
// read string in the file into array of character, `word` until reaching end of the file
char word[LENGTH + 1];
while (fscanf(file, "%s", word) != EOF)
{
// keep track of how many word exists in the file, for later use (not in this function)
word_counter += 1;
// allocated memory for struct type `node`, if not enough memory found, return false
node *n = (node*)malloc(sizeof(node));
if (n == NULL)
{
return false;
}
// assign index by hashing (hash function will not be posted in this question though.)
unsigned int index = hash(&word[0]);
// copy the word from file, into word field of struct type `node`
strncpy(n->word, word, sizeof(word));
// Access the node pointer in this index from array(table), and check is its `next` field points to NULL or not.
// If it is pointing to NULL, that means there is no word stored in this index of the bucket
if (table[index]->next == NULL) // THIS IS WHERE PROGRAM GIVES 'segmentation fault' !!!! :(
{
table[index]->next = n;
}
else
{
n->next = table[index];
table[index]->next = n;
}
}
return true;
}
Upvotes: 0
Views: 217
Reputation: 409384
You define ant initialize the hash table as:
node *table[N] = {NULL};
That means you have an array of null-pointers.
When you insert the first value in the table, then table[index]
(for any valid index) will be a null pointer. That means table[index]->next
attempt to dereference this null pointer and you will have undefined behavior.
You need to check for a null pointers first:
if (table[index] == NULL)
{
n->next = NULL;
}
else
{
n->next = table[index];
}
table[index] = n;
Upvotes: 1