Reputation: 403
The following is a code that inserts in a hashtable (obviously) developed in the openCV contrib branch. I suspect there is a memory leak in the code. The reason I suspect that is that I read the hashtable from a file ~200 MB in size and when I check the memory consumed by the program when it runs in a matter of seconds it exceeds 1GB, and if I let it run for some time the entire operating system crashes as it exceeds 6 GB.
I know a bit about C, but I want to make sure that this is the case. If there is a memory leak how can I fix it?
int hashtableInsert(hashtable_int *hashtbl, KeyType key, void *data){
struct hashnode_i *node;
size_t hash=hashtbl->hashfunc(key)%hashtbl->size;
node=(hashnode_i*)malloc(sizeof(struct hashnode_i));
if (!node)
return -1;
node->key=key;
node->data=data;
node->next=hashtbl->nodes[hash];
hashtbl->nodes[hash]=node;
return 0;
}
Upvotes: 1
Views: 275
Reputation: 5240
I couldn't spot the memory leak (if there is one), but of course you can use the memory leak checker valgrind
. You run it during runtime.
If you cannot understand how to use it from the link I mentioned, do this:
Let's take your program, as
hash.c
. Got to the command line and compile it, for eg :gcc hash.c -Wall
If your program compiles successfully, an executable or
out
file will appear. As we have not specified the name of the executable, it's default name will bea.out
. So let's run it withvalgrind
:valgrind -- leak-check=full ./a.out
This will run executable, along with valgrind, and if there is a memory leak, it will show it when the executable ends.
If you do not have
valgrind
installed, you can install it from here.
Upvotes: 2