所以我有一个带有 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/