i have written this code for pset5 dictionary.c
i loaded dictionary in trie data structure. it shows segmentation fault.
/**
* Implements a dictionary's functionality.
*/
#include <stdbool.h>
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include "dictionary.h"
typedef struct node
{
char n;
struct node *next;
}node;
int words = 0;
node *head , *temp;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
temp = head;
int count = 0;
int l = strlen(word);
for(int i=0;i<l;i++)
{
if(temp[word[i]-'a'].n == word[i])
{
temp = temp[word[i] - 'a'].next;
count++;
}
else
break;
}
if(count == l)
{
return true;
}
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
int i = 0;
head = temp = malloc(26*sizeof(node));
for(i=0;i<26;i++)
{
head[i].n = '0';
head[i].next = NULL;
}
FILE *ptr = fopen(dictionary,"r");
if (ptr == NULL)
{
printf("Could not open dictionary");
return false;
}
while(feof(ptr))
{
char *d= NULL;
fscanf(ptr,"%s",d);
words++;
int l = strlen(d);
for(int j=0;j<l;j++)
{
if(temp[d[j] - 'a'].next == NULL)
{
temp[d[j] - 'a'].n = d[j];
temp[d[j] - 'a'].next = malloc(26*sizeof(node));
temp = temp[d[j] - 'a'].next;
for(int k=0;k<26;k++)
{
temp[k].n = '0';
temp[k].next = NULL;
}
}
else
{
temp = temp[d[j] - 'a'].next;
}
}
temp = head;
}
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
if(words != 0)
return words;
return 0;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
free(head);
free(temp);
return true;
}
but it shows segmentation fault. i tried experimenting with my trie code and it worked fine with other codes. output :-
Segmentation fault