I cannot figure what's wrong with the code, it gives me a segfault, but runs in valgrind and in gdb. So far, i only wrote the load function, so anything else is still empty.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dictionary.h"
typedef struct node
{
bool is_word;
struct node* children[27];
}
node;
int size_dict;
bool load(const char* dictionary)
{
// TODO
node* root = NULL;
node* new = NULL;
node* curr = NULL;
FILE* dict = fopen(dictionary, "r");
if (dict == NULL)
{
printf("Could not open %s.\n", dictionary);
unload();
return 1;
}
int index = 0;
char entry[LENGTH + 1];
char c = ' ';
size_dict = 0;
int idx_ltr = 0;
root = malloc(sizeof(node));
for(int i = 0; i < 27; i++)
{
root -> children[i] = NULL;
}
do
{
fread(&c, sizeof(char), 1, dict);
while(c != '\n')
{
entry[index] = c;
index++;
fread(&c, sizeof(char), 1, dict);
}
entry[index] = '\0';
curr = root;
int counter = 0;
do
{
if(entry[counter] == '\'')
{
idx_ltr = 26;
}
else
{
idx_ltr = entry[counter] - 'a';
}
if(counter + 1 == index)
{
if (curr -> children[idx_ltr] == NULL)
{
curr -> children[idx_ltr] = curr;
curr -> is_word = true;
break;
}
}
else
{
new = malloc(sizeof(node));
for(int j = 0; j < 27; j++)
{
new -> children[j] = NULL;
}
curr -> children[idx_ltr] = new;
curr = new;
counter++;
}
}while(counter < index);
size_dict++;
index = 0;
}while(!feof(dict));
fclose(dict);
printf("%i\n", size_dict);
return true;
}
Still, i think it's also buggy when building the trie, since when running valgrind i get this definitely lost blocks, and using small dictionary i should have only 11 mallocs (1 for root + 2 for cat and + 8 erpillar):
==10751==
==10751== HEAP SUMMARY:
==10751== in use at exit: 1,568 bytes in 14 blocks
==10751== total heap usage: 16 allocs, 2 frees, 2,272 bytes allocated
==10751==
==10751== Searching for pointers to 14 not-freed blocks
==10751== Checked 57,456 bytes
==10751==
==10751== LEAK SUMMARY:
==10751== definitely lost: 336 bytes in 3 blocks
==10751== indirectly lost: 1,232 bytes in 11 blocks
==10751== possibly lost: 0 bytes in 0 blocks
==10751== still reachable: 0 bytes in 0 blocks
==10751== suppressed: 0 bytes in 0 blocks
==10751== Rerun with --leak-check=full to see details of leaked memory
==10751==
==10751== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==10751== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Sorry, but i'm desperate cause the course ends in the 31th, and i got a license from work to do it,so i must manage to end it (all others pset's are done). Thank you guys.