c - 为什么我的程序有内存泄漏检查错误?

标签 c memory-management memory-leaks valgrind

当我使用它时

valgrind --leak-check=yes ./Main

我有大约 185236 个错误。它说:

xx bytes in x blocks are possibly lost in loss record xxxx of xxxx

这是我的代码:

Node InsertString(Head head, Node tree, char* data) {
    if (tree == NULL) {
        tree = malloc(sizeof (struct TreeNode)); //Error

        if (tree == NULL) {
            printf("Out of Space!\n");
        } else {
             tree->theData = malloc(sizeof (char) * strlen(data));//Error
            strcpy(tree->theData, data);
        }
    } else {
            if (strcmp(data, tree->theData) < 0) {
                tree->Left = InsertString(head, tree->Left, data); //Error
            } else {
                if (strcmp(data, tree->theData) > 0) {
                    tree->Right = InsertString(head, tree->Right, data);//Error
                }
            }
        } 

    }
    return tree;
}

谢谢!

最佳答案

你有没有调用过free来释放你用malloc分配的内存?

如果不是,好吧,那么你正在泄漏所有的内存。

关于c - 为什么我的程序有内存泄漏检查错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4543774/

相关文章:

c - karger Minimum Cut 算法因大输入而崩溃

c++ - 有没有更好的方法来实现这种内存管理?

c++ - 如何计算 C++ 中应用程序消耗的总内存和 CPU 使用率?

c++ - 算术运算和编译器优化

c++ - 函数参数求值顺序

c - 如何在不引入锁定的情况下编写并发读取和修改定义明确的数组的代码?

c++ - 类中的内存使用 - 将 double 转换为 float 并没有像预期的那样减少内存使用

iphone - 解析 xml 时 NSCFString appendString 泄漏

java - 弱引用 : reference is destroyed within "seconds"

ios - 将文本分配给 UILabel 时发生内存泄漏(iOS、Swift 4、Xcode 9)