以下是插入在 openCV contrib 分支中开发的哈希表(显然)的代码。我怀疑代码中存在内存泄漏。我怀疑的原因是我从一个大小约为 200 MB 的文件中读取哈希表,当我检查程序在几秒钟内运行时消耗的内存超过 1GB,如果我让它运行一段时间整个操作系统崩溃,因为它超过 6 GB。
我对 C 语言略有了解,但我想确保情况确实如此。如果存在内存泄漏,我该如何修复?
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;
}
最佳答案
我无法发现内存泄漏(如果有的话),但是您当然可以使用内存泄漏检查器 valgrind
.您在运行时运行它。
如果您无法从我提到的链接中理解如何使用它,请执行以下操作:
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.
关于C潜在的内存泄漏malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626736/