I saw a similar question about memory leaks with speller "pset5 valgrind memory leaks", but that poster found a solution that doesn't seem to work at all for my program. Just like that user, I get about twice as many allocs in valgrind as the number of entries in the dictionary, as well as twice the number of frees shown.
They solved this by changing part of their struct definition to char*. Here's my struct definition and related variables:
//list structure
typedef struct node
{
char word[LENGTH + 1];
struct node* next;
}node;
node* hashtable[hsize];
node* new_node;
node* cursor;
It seems that if I change the declaration of word within my struct I get a seg fault (if changed to char*) or "incompatible pointer types" if I change it to char* word[LENGTH + 1].
Here's my unload function:
[hidden behind edit flag]
So, my question is: how is my struct definition related to this inefficiency in unload? It seems, because of the numbers(2x as many allocs as dictionary entries and as frees) like free is only freeing part of each node and malloc is being called for each struct component separately. Is this possible?
Here's my load function:
[hidden behind edit flag]
and the valgrind output:
HEAP SUMMARY:
==3069== in use at exit: 6,510,908 bytes in 125,204 blocks
==3069== total heap usage: 268,297 allocs, 143,093 frees, 13,952,044 bytes
==3069== Allocated
==3069== 6,510,556 bytes in 125,203 blocks are definitely lost in loss
==3069== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-
x86-linux.so)
==3069== by 0x8049087: check (dictionary.c:59)
==3069== by 0x8048B6D: main (speller.c:117)
==3069==
==3069== LEAK SUMMARY:
==3069== definitely lost: 6,510,556 bytes in 125,203 blocks
==3069== indirectly lost: 0 bytes in 0 blocks
==3069== possibly lost: 0 bytes in 0 blocks
==3069== still reachable: 352 bytes in 1 blocks
node* tmp = malloc(something);
followed by a reassignment to tmp liketmp = node->next;
This is a very common error in this exercise - creating a pointer and initializing with a malloc or calloc call and then reassigning the pointer to something else, thus losing the originally malloc'd memory. In this case, it should have been initialized to NULL instead of malloc'd. – Cliff B Sep 13 '15 at 19:57