0

My code is leaking just 276 bytes of memory in pset 5, and I am at a loss to understanding where it is.

Using help50 and valgrind, I get the advice:

Looks like your program leaked 276 bytes of memory. Did you forget to free memory that you allocated via malloc? Take a closer look at line 40 of dictionary.c.

The summary of the leakage is: ==10620== HEAP SUMMARY: ==10620== in use at exit: 276 bytes in 6 blocks ==10620== total heap usage: 143,103 allocs, 143,097 frees, 8,023,683 bytes allocated ==10620== ==10620== 276 bytes in 6 blocks are definitely lost in loss record 1 of 1

bool check(const char *word)
{
    char *temp_string = malloc(LENGTH + 1); //this is line 40.
    int k = 0;

    strcpy(temp_string, word);

    while (*(word + k) != (char) 0)
    {
        *(temp_string + k) = tolower(*(temp_string + k));
        k++;
    }

    if (table[hash(temp_string)] == NULL)
    {
        return false;
    }

    else
    {
        return is_in(table[hash(temp_string)], temp_string);
    }

    free(temp_string);
}
1

Here's the thing about valgrind. It will tell you which line is allocating the memory, but not how it's leaking. This is still a big help. In this case, it made it easy.

Take a careful look at the check function. Is there any execution path that will ever reach the free statement? Or do all paths end with a return statement prior to the free statement. Remember, when a return statement is executed, nothing further in a function will be executed. If the free statement is never being executed, you will have a nasty memory leak - a block of memory for every word checked. (If you want to verify this, put a printf statement just before or after the free statement. See if it executes.)

Maybe it would be better to allocate a char array instead of mallocing temp memory?

When a fixed amount of memory is needed, particularly a single variable or array, it's often better to just create a standard variable, rather than a pointer to malloc'd memory. Dynamically allocated memory is more appropriate for dealing with allocating an undetermined amount of memory at execution time. In this case, there's no need for this type of memory allocation (other than more practice). A simple char array or string will do the job. It also means far less overhead.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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