``Thanks for your help so far on pset5. I have been able to implement pset5, the code is working properly, passed check50 but the output does not match the staff output. For instance, when tested with alice.txt, my code gives over 1,000 errors while that of the staff gives just 644 errors. Moreover, valgrind shows quite a lot of memory loss. Please check through my code and advice me where I got it wrong. Thanks so much.
/**
* dictionary.c
*
* Computer Science 50
* Problem Set 5
*
* Implements a dictionary's functionality.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "dictionary.h"
#define ALPHABETS 27
typedef struct node
{
bool is_word;
struct node* children[ALPHABETS];
} node;
node* root = NULL;
int counter =0;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
// TODO
node* current = root;
int w_index;
int w_len = strlen(word);
for(int i = 0; i < w_len; i++)
{
if(isalpha(word[i]))
{
if(isupper(word[i]))
w_index = (tolower(word[i])) - 'a';
else
w_index = word[i] - 'a';
}
else if (word[i] == '\'')
{
w_index = 26;
}
if(current->children[w_index] == NULL)
{
current->is_word = false;
return false;
}
else
current = current->children[w_index];
}
if(current->is_word == true)
return true;
else
return false;
return true;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
// TODO
char d_word[LENGTH +1];
root = (node*)malloc(sizeof(node));
if(root)
{
int i;
root->is_word = false;
for(i = 0; i < ALPHABETS; i++)
root->children[i] = NULL;
}
FILE* file = fopen(dictionary, "r");
if (file == NULL)
{
printf("Could not open %s.\n", dictionary);
unload();
return 1;
}
int index;
while(fscanf(file, "%s", d_word)!= EOF)
{
node*trav = root;
int length = strlen(d_word);
for(int j = 0; j < length; j++)
{
if(isalpha(d_word[j]))
index = d_word[j] - 'a';
else if(d_word[j] == '\'')
index = 26;
if(trav->children[index] == NULL)
trav->children[index] = malloc(sizeof(node));
trav = trav->children[index];
}
trav->is_word = true;
counter++;
}
fclose(file);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
// TODO
return (counter);
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
// TODO
node* temp;
node* cursor = root;
for(int i = 0; i < ALPHABETS; i++)
{
if (cursor->children[i] != NULL)
{
temp = cursor;
cursor = cursor->children[i];
continue;
}
else if(temp != NULL)
{
free(temp);
temp = NULL;
}
}
return true;
//return false;
}