I am having some headaches about pset5.
Before tackling hashtables and tries, I have been trying to solve the problem with a single linked list to make it simpler. To do this I have defined a couple of global variables because they have to be used in more than one function ("node *head" in load() and check(); "int dictionary_size" in load(), size() and unload()).
Something is fishy about the head node, but I can't get what it is: I have tried using debug50 (head is not shown to me as a struct node but simply as a pointer, even after I have defined it and allocated memory for it, or that's what I think I've done).
Could anybody give me a hint about where the root cause of this problem is?
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "dictionary.h"
// Define struct node
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Initialize global variables
node *head = NULL;
int dictionary_size = 0;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// Create a cursor to navigate through the linked list in search of the word
node *cursor = head;
// Go on until cursor reaches the end of the lls and return true if the word is found
while (!cursor)
{
if (strcasecmp(cursor -> word, word) == 0)
{
return true;
}
cursor = cursor -> next;
}
return false;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
FILE *file = fopen(dictionary, "r");
char wordsy[LENGTH + 1];
if (fscanf(file, "%s", wordsy) != EOF)
{
head = malloc(sizeof(node));
// Check memory availability for the head node
if (!head)
{
unload();
return false;
}
// Copy the word from dictionary inside the node and increase the size of the dictionary by one
strcpy(head -> word, wordsy);
dictionary_size++;
while (fscanf(file, "%s", wordsy) != EOF)
{
node *node = malloc(sizeof(node));
// Check memory availability for the node
if (!node)
{
unload();
return false;
}
// Copy the word from dictionary inside the node and increase the size of the dictionary by one
strcpy(node -> word, wordsy);
dictionary_size++;
// Insert the new node in the linked list and update its head
node -> next = head;
head = node;
}
return true;
}
return false;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
if (loaded)
{
return dictionary_size;
}
return 0;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// Set counter
int m = 0;
node *cursor = head;
while (!cursor)
{
node *temp = cursor;
cursor = cursor -> next;
free(temp);
m++;
}
// Check that all the nodes got freed
if (m == dictionary_size)
{
return true;
}
else
{
return false;
}
}