I've been getting a seg fault in load on this line: buckets[hash_num] = buffer_node;
.
I have read most if not all the posts on seg faults in load, and can't seem to figure mine out. At first I thought it was because the pointer buckets[hash_num] was not allocated memory, so by assigning buffer_node to it, I was creating the seg fault. However when I tried to malloc memory to buckets[hash_num] (as seen in the commented out code below), the code does not even compile.
A check on valgrind shows there are no errors.
I don't know if this matters, but the segfault happens only after I've successfully loaded a few words into dictionary and I hit the first capitalized word.
Any help would be much appreciated. I'm totally new to programming. I've been at this for days now and I am quite clueless how to proceed.
typedef struct node
{
char dictionary_word[LENGTH + 1];
struct node* next;
}
node;
//prototypes and global variables
int hash_num;
int isupper(int c);
int hash(const char* dictionary_word);
int words_loaded = 0;
// Create array of buckets, one for each hash
node* buckets[26];
// I tried to malloc each element in array, but code wouldn't compile.
//for (int i = 0; i < 26; i++)
//{
// buckets[i] = malloc(sizeof(node));
//}
bool load(const char* dictionary)
{
//struct defined on top
//array of buckets / pointers to linked list declared globally
//Open Dictionary
FILE* dictionary_ptr = fopen(dictionary, "r");
if (dictionary_ptr == NULL)
{
printf("fail to open dictionary\n");
return false;
}
//array to store word
char buffer[LENGTH + 1];
//malloc a node called buffer_node for the new word
node* buffer_node = malloc(sizeof(node));
//scan dictionary file, load words into buffer
while (fscanf(dictionary_ptr, "%s", buffer) == 1)
{
//generate hash number of buffer
hash_num = hash(buffer);
// copy the buffer word into the node field
strcpy(buffer_node -> dictionary_word, buffer);
//link node's pointer to NULL if that bucket is empty, else link it to the first node in bucket.
if (buckets[hash_num] == NULL)
{
buffer_node -> next = NULL;
}
else
buffer_node -> next = buckets[hash_num];
buckets[hash_num] = buffer_node; //keep getting a seg fault here
//clock word upload
words_loaded += 1;
printf("%i, %s saved to memory success\n", words_loaded, buffer);
//jump to next line
}
fclose(dictionary_ptr);
printf("dictionary saved successfully\n");
free(buckets);
free(buffer_node);
return(true);
}