0

I wrote the following code for the Unload() function of pset6 :

bool unload(void)
{
    node* pred = NULL;
    for(int i = 0; i < capacity; i++)
    {
       nextnode = hasharray[i];
       while(nextnode != NULL)
       {
           pred = nextnode->next;
           free(nextnode);
           nextnode = pred;
       }
    }

    free(pred);
    free(nextnode);
    return true;
}

I have tried implementing a hash table for the problem set. Though the code runs fine but when I check with valgrind then it shows memory leaks implying that the memory was not freed.

Can anyone suggest why is it so?

Thanks.

2
  • Do the nodes contain any data that has allocated memory on the heap (e.g., strings)?
    – kzidane
    Jun 19 '14 at 9:20
  • @Kareem yes each node structure has 3 values - tag,name,nextnode address
    – Harsh
    Jun 19 '14 at 9:30
3

You have to free the data you allocated memory for separately within the nodes before you free the nodes themselves.

For example,

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    // create a new struct
    struct Node
    {
        char *str;
    };

    // create a new pointer
    struct Node *ptr = malloc(sizeof(struct Node));

    // allocate memory for str
    ptr -> str = malloc(sizeof("hi"));

    // initialize str
    strcpy(ptr->str, "hi");

    // free memory
    free(ptr -> str); // because we allocated memory for this separately
    free(ptr);
}

This way, you won't get any leaks as shown here:

kareem@kareem:~$ valgrind --leak-check=full ./example
==3732== Memcheck, a memory error detector
==3732== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3732== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==3732== Command: ./example
==3732== 
==3732== 
==3732== HEAP SUMMARY:
==3732==     in use at exit: 0 bytes in 0 blocks
==3732==   total heap usage: 2 allocs, 2 frees, 12 bytes allocated
==3732== 
==3732== All heap blocks were freed -- no leaks are possible
==3732== 
==3732== For counts of detected and suppressed errors, rerun with: -v
==3732== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
4
  • Thanks a lot buddy. I had forgotten about the memory that i had allocated to the char*.
    – Harsh
    Jun 19 '14 at 9:58
  • can you please explain why don't we need to free the str by using a loop to iterate through str0,1and 2? Apr 1 '15 at 6:25
  • @FlorenceWu we call free on a pointer returned by malloc, calloc, or realloc. In this case, we stored the pointer returned by malloc into str. So we call free on str. Also, str[0], str1[1], ... are not really pointers. They're chars.
    – kzidane
    Apr 1 '15 at 10:40
  • i see, think you ;) Apr 1 '15 at 13:48

You must log in to answer this question.

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