I'm currently doing the load part of pset 5 and I ran into a problem I was not yet able to solve. This is my code:
bool load(const char* dictionary)
{
FILE* dic = fopen(dictionary, "r");
typedef struct node {
bool is_word;
struct node* children[27];
} node;
node* root = (node*) malloc(sizeof(node*));
char* word = (char*) malloc(45);
int length = 0;
while (true){
fscanf(dic, "%s", word);
while (isalpha(word[length]) || word[length] == '\''){
length++;
}
while (length > 0){
node* newroot = root;
for (int i = 0; i < length; i++){
if (newroot->children[word[i]-'a'] == NULL){ // The error happens here
newroot->children[word[i]-'a'] = (node*) malloc(sizeof(node*));
newroot = newroot->children[word[i]-'a'];
}
else
{
newroot = newroot->children[word[i]-'a'];
}
if (i == length-1){
newroot->is_word = true;
length = 0;
}
}
}
}
return false;
}
I tried using GDB and it goes like this (word being read is 'cat') : When mallocing in the declaration of root, most of the root's children are null but some have a value, one of the children with value is at index 2 representing c (all of the c's children are of value NULL). Therefore during the first iteration of the for loop the else code block is executed and newroot is changed. During the second iteration the segmentation fault happens on the line with the comment. My guess is there is something wrong with how i try to malloc the null pointer but i honestly don't know. Thank you for every answer.