C潜在的内存泄漏malloc

标签 c opencv memory-leaks

以下是插入在 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 be a.out. So let's run it with valgrind:

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/

相关文章:

通过电阻器上的颜色计算电阻

java - 使用 C 语言通过 FFmpeg 保存部分视频

c - C 中的空指针

c++ - opencv中有DWT函数吗?

PHP "Uninclude"或从内存中删除?

c++ - 内存泄漏问题

java无限循环调用datainputstream收到内存不足异常

objective-c - 为什么在我的 Objective-C 代码中间接调用时此 C 数组为 NULL? (cocos2d)

c++ - 为什么在 OpenCV 中访问此矩阵时出现内存错误?

android - OpenCV 未定义对 cv::SURF::SURF() eclipse 的引用