So I've been working my way through PSet5, and I can't seem to find out why I have a segmentation fault here, or why I get an endless loop. It says the fault is on line 31, which I'll mark in the code (it's part of check()), but I also copied load() just in case there's a part of the problem there too.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "dictionary.h"
typedef struct node {
bool is_word;
struct node* children[27];
}
node;
node* root;
int wordNum = 0;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
// TODO
node* character = root;
for (int i = 0; i < strlen(word); i++) { //this seems to be the line with the segmentation fault
int chara = toupper(word[i]) - 'A';
if(character->children[chara] != NULL) {
character = character->children[chara];
} else {
return false;
}
}
return character->is_word;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
// TODO
FILE* dict = fopen(dictionary, "r");
node* character = root;
wordNum = 0;
for (int c = fgetc(dict); c != EOF; c = fgetc(dict))
{
if(c != '\n') {
int chara = toupper(c) - 'A';
if(character->children[chara] == NULL) {
character->children[chara] = (struct node*) malloc (sizeof(node));
}
character = character->children[chara];
} else {
character->is_word = true;
character = root;
wordNum++;
}
}
if(fgetc(dict) == EOF) {
return true;
} else {
return false;
}
}
If someone could give me some pointers (ba dum tsss) to help me get on the right way and solve my problem, that would be great. I've been at this specific problem for the last few hours now.