0

my implementation of dictionary.c passes all checks using check50 except memory leaks. I'm using valgrind and most of my leaks seem to be happening in my check function:

// Returns true if word is in dictionary else false
bool check(const char* word)
{
    // TODO
    bool result = false;
    char* tmp = malloc(sizeof(word) + 1);
    strcpy(tmp, word);

    for (int i = 0; i < strlen(tmp); i++)
    {
        tmp[i] = tolower(tmp[i]);
    }

    int index = hash(tmp);
    node* n = arr[index];
    while (n != NULL)
    {
        if (strcmp(n->w, tmp) == 0)
        {
            result = true;
            break;
        }
        n = n->next;
    }

    free(tmp);

    return result;
}

The reason I am using tmp is because I can't use tolower on char* word because it's a constant.

2

Did you know that sizeof(word) returns the length of the word variable? That's right, 8 bytes on a 64-bit system. The variable stores a memory address of the first byte of the string (stored somewhere else).

You meant strlen instead.

Not sure how this can be related to a memory leak, but it's clearly a potential out-of-bounds access.

BTW, if you used it like char tmp[strlen(word) + 1];, you wouldn't need free(tmp); later, as this would allocate the memory on stack, and the stack pointer is reset on returning from the function, declaring the newly allocated stack memory unused.

| improve this answer | |
  • Thanks for the help, Blauelf. – JohnWick Mar 8 '18 at 22:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .