c++ int指向数组指针数组的指针内存泄漏

标签 c++

所以我有一个带有 functions.hpp 和 functions.cpp 的类

#include "function.hpp"

test::test(int size)
{
    this->size = size;
    matrix = new int*[this->size];
    for (int i = 0; i < size; i++)
    {
        matrix[i] = new int[this->size];
    }
}

test::~test()
{
    for (int i = 0; i < this->size; i++)
        delete[] this->matrix[i];
    
    delete[] this->matrix;
}

但这仍然会产生内存泄漏,我正在使用CRT库进行测试

#include "function.hpp"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    int size = 10;
    test test(size);
    _CrtDumpMemoryLeaks();
    return 0;
}

此代码仍然向我转储内存泄漏,我已经学习了几个教程,但我开始怀疑 CRT 库或我的计算机。

最佳答案

问题是析构函数直到 main 退出时才会被调用,这是您调用 _CrtDumpMemoryLeaks 之后。将您的代码更改为此

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    {
        int size = 10;
        test test(size);
    }
    _CrtDumpMemoryLeaks();
    return 0;
}

额外的 {} 确保在调用 _CrtDumpMemoryLeaks 之前调用析构函数。

另一种技术是编写一个类来执行检查。

class LeakCheck
{
public:
    LeakCheck() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); }
    ~LeakCheck() { _CrtDumpMemoryLeaks(); }
    LeakCheck(const LeakCheck&) = delete;
    LeakCheck& operator=(const LeakCheck&) = delete;
};

int main()
{
    LeakCheck _checker;
    int size = 10;
    test test(size);
    return 0;
}

因为析构函数的调用顺序与构造函数相反,所以可以保证 _CrtDumpMemoryLeaks 会在 test 的析构函数之后被调用。

我想将 LeakCheck 称为 填充类 但显然这不是正确的术语,也许有人可以在评论中告诉我正确的术语。

关于c++ int指向数组指针数组的指针内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63242484/

相关文章:

c++ - unique_ptr 的默认值

c++ - 组合两个不同类型的 std::lists:可能吗?

c++ - 从头文件中的命名空间访问类型

c++ - 添加到动态库中的函数指针映射

c++ - Boost.Exception 符号出现在 'nm' 输出中是什么意思?它们会导致 ODR 违规吗?

c++ - 用动态数组模拟的单链表

c++ - 尝试使用QT的网络库时报错2027

c++ - 源码中的防火墙绕过技术

c++ - EasyBMP c++ 的 RGBApixel 内存问题

c++ - 基本示例的 V8 编译错误