目前,我有一个解决方案,但不确定在每种情况下是否都可以。使用此解决方案,我可以检查程序中是否存在内存泄漏?如果有人可以提供更好的解决方案,请随时分享答案。谢谢!
我的示例代码在这里:
int *array = new int[5];
delete[] array; //so no memory leaks
//Memory leak check.
if (_CrtDumpMemoryLeaks()) {
std::cout << "Memory leaks!\n";
}
else {
std::cout << "No leaks\n";
}
cin.get();
return 0;
最佳答案
在您的情况下,最合适的方法就是您一开始就使用CRT
库,实际上是按照Microsoft文档的说明使用_CrtDumpMemoryLeaks();
:
The _CrtDumpMemoryLeaks function determines whether a memory leak has occurred since the start of program execution.
关于您的其他疑问:
but I am not sure if it's alright in every scenario
根据Microsoft文档,它应该记录整个程序中发生的所有内存泄漏,即使它在类中或您可能认为的任何位置:
Dumps all the memory blocks in the debug heap when a memory leak has occurred
同样不要忘记对
#define
标志进行_DEBUG
,如此处所述:When _DEBUG is not defined, calls to _CrtDumpMemoryLeaks are removed during preprocessing.
但是,如果要制作软件,则应该使用STL并使用智能指针。
另外,您可能还可以使用另一种方式来一次检查某个资源的内存泄漏,在调试时,我使用Visual Studio提供的内存选项卡,该选项卡位于调试> Windows>内存> memory1 (注意:进入 Debug模式以查看设置),然后在搜索栏中键入
array
,以便转到指向内存的位置,然后可以进入程序并查看内存是否被清空。注意:
如果您想一次以视觉方式监视一个资源,而不是想要每个可能泄漏的资源都进行完整转储,则这样做的效果更好。
关于c++ - C++ Microsoft Visual Studio 2017最佳和最简单的检测内存泄漏的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62048688/