0

cant find where is the memory leak here is my code

// Implements a dictionary's functionality
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include "dictionary.h"
#include <cs50.h>
#include <stdlib.h>

int main()
{
    return 1;
}
// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// TODO: Choose number of buckets in hash table
const unsigned int N = 26 * 26;
int words_count = 0;

// Hash table
node *table[N];

// Returns true if word is in dictionary, else false
bool check(const char *word)
{
    // TODO
    int index = hash(word);
    node *n = table[index];
    // checking Null pointer
    while (n != NULL)
    {
        // comparing
        if (strcasecmp(n-> word, word) == 0)
        {
            return true;
        }
        else
        {
        n = n -> next;
        }
    }
    return false;
}

// Hashes word to a number
unsigned int hash(const char *word)
{
    // returning hash
    return (int) (toupper(word[0]) - 'A') * (toupper(word[1]) - 'A');
}

// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
    // opening our dict
    FILE *file = fopen(dictionary, "r");
    // checking NULL pointer
    if (file == NULL)
    {
        return false;
    }
    // initializing
    char word[LENGTH + 1];
    while (fscanf(file, "%s", word) != EOF)
    {
        //incrementing
        words_count += 1;
        //allocating mem
        node *n = malloc(sizeof(node));
        // checking if NULL pointer
        if (n == NULL)
        {
            return false;
        }
        //copying word into the node
        strcpy(n -> word, word);
        //hashing
        int index = hash(word);
        if(table[index] != NULL)
        {
           n -> next = table[index];
        }
        else
        {
            n -> next = NULL;
        }

        table[index] = n;
    }
    fclose(file);
    return true;
}

// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
    // retruning
    return words_count;
}

// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
    // TODO
    node *n = NULL;
    node *tmp = NULL;
    for (int index = 0; index < N; index++)
    {
        n = table[index];
        while (n != NULL)
        {
            tmp = n;
            n = n -> next;
            free(tmp);
        }
    }
    return true;
}
2
  • what did valgrind have to say?
    – Cliff B
    Commented Sep 20, 2022 at 18:55
  • A quick scan of the code raises the question: You do know there are one letter words in the dictionary, right? Commented Sep 21, 2022 at 12:34

0

You must log in to answer this question.

Browse other questions tagged .